I am quite new in writing JS-rules. In general my JS-rules are working. But I would like to create a new rule using the Axios-library. The library was installed successfully (I guess).
But when I am trying to “require” the axios library with: const axios = require('axios'); I am getting the error message below.
I am using Openhabian and my openhab version is 3.4.4
Can anyone give me a hint how to solve it?
Error message:
org.graalvm.polyglot.PolyglotException: SyntaxError: /etc/openhab/automation/js/node_modules/axios/index.js:1:94 Expected an operand but found import
(function (exports, require, module, __filename, __dirname) {require=__wraprequire__(require);import axios from './lib/axios.js';
^
/etc/openhab/automation/js/node_modules/axios/index.js:24:0 Expected an operand but found export
export {
^
/etc/openhab/automation/js/node_modules/axios/index.js:25:8 Expected ; but found as
axios as default,
^
/etc/openhab/automation/js/node_modules/axios/index.js:43:0 Expected ) but found }
});
^
/etc/openhab/automation/js/node_modules/axios/index.js:43:1 Expected ; but found )
});
OH provides a NodeJS like environment but not a fully compatible environment. And certain underlying constructs like require are actually implemented by the underlying Java, not the GraalVM JS environment. So there will definitely be many third party node modules that won’t work. I’m not surprised it has problems with export.
Everything Rich wrote is correct.
JavaScript Scripting is only a NodeJS-like environment that supports much stuff, but it has limitations compared to real NodeJS.
It seems like Axios is using ES Module Loading which is not supported by JavaScript Scripting. Even if it was supported, Axios still wouldn‘t work because the native NodeJS APIs such as node:http aren‘t available in GraalJS (at least in the mode we have to run it).
And Promise-based stuff is also not supported.
If you want to perform HTTP operations, you can use the HTTP actions (actions - Documentation).
I think you haven’t read my reply carefully …
As already said, Axios won’t work (no matter what the docs say) because it needs some type of NodeJS HTTP API which is not available in openHAB JavaScript Scripting.
And XmlHTTPRequest isn’t supported as well.
Use the HTTP actions:
var response = actions.HTTP.sendHttpGetRequest(String url);
var json = JSON.parse(response);