Write an SIE script in Node.js
From version 18, Node.js has fetch built in, so a script that reads a REST API needs no packages at all. It suits teams that already write JavaScript.
Good for
- REST APIs and JSON.
- Teams that already maintain JavaScript tooling.
Set it up
Install Node.js 18 or later from your OS packages or NodeSource, then check:
node --version # v18 or laterwhich node # use this path in the commandIf a script needs npm packages, give it a folder of its own inside the scripts folder (for example node/) and run npm install there, as root, then make the folder readable by the web user. Node finds packages in a node_modules folder next to the script, so the command just points at {script_path}node/my-script.mjs.
The command
/usr/bin/node {script_path}my-script.mjs {device_ip} {device_password}A minimal script
This one reads a JSON config from an HTTPS API with a bearer token, and prints it with keys sorted:
// Minimal SIE script in Node.js: fetch a JSON config over HTTPS.//// Usage: node node-skeleton.mjs <host> <token>
const note = (message) => console.error(message);const fail = (message) => { console.error(`ERROR: ${message}`); process.exit(1); };
// Sort object keys at every level, so the stored text doesn't depend on API order.const sortKeys = (value) => Array.isArray(value) ? value.map(sortKeys) : value && typeof value === "object" ? Object.fromEntries(Object.keys(value).sort().map((k) => [k, sortKeys(value[k])])) : value;
const [host, token] = process.argv.slice(2);if (!host || !token) fail("usage: node-skeleton.mjs <host> <token>");
const url = `https://${host}/api/config`; // adapt for your devicenote(`fetching config from ${host}`);
let data;try { const response = await fetch(url, { headers: { Authorization: `Bearer ${token}`, Accept: "application/json" }, signal: AbortSignal.timeout(30_000), }); if (!response.ok) fail(`HTTP ${response.status} from ${host}`); data = await response.json();} catch (error) { fail(`request to ${host} failed: ${error.message}`);}
if (!data || (typeof data === "object" && Object.keys(data).length === 0)) { fail("empty config, refusing to store it");}
process.stdout.write(JSON.stringify(sortKeys(data), null, 2) + "\n");note(`SIE-OK: node config from ${host}`);Habits that matter in Node.js
console.errorfor progress,process.stdout.writefor the config.console.loggoes to stdout and is stored..mjsfor top-levelawait. The file extension makes Node treat the script as a module.- A timeout on every request.
AbortSignal.timeoutstops a stalled request before rConfig’s timeout does.
Related
- Python for the same job on the system Python
- HTTP APIs: curl and requests