Running a command in JavaScript
execFile with an argument array, promisified and awaited.
import { execFile } from "node:child_process";
import { promisify } from "node:util";
const run = promisify(execFile);
const { stdout } = await run(process.execPath, ["-e", "console.log(21 * 2)"]);
console.log(stdout.trim());
try {
await run(process.execPath, ["-e", "process.exit(3)"]);
} catch (error) {
console.log("exit code:", error.code);
}
How it works
- Pass arguments as an array: no shell, no quoting bugs.
- The promise rejects on a non-zero exit, carrying stderr.
spawnis the streaming alternative for large output.
Keywords and builtins used here
awaitcatchconstfromimporttry
The run, in numbers
- Lines
- 13
- Characters to type
- 349
- Tokens
- 86
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 47 seconds.
Step 2 of 3 in Crypto & processes, step 16 of 18 in Node.js.