typestar

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

  1. Pass arguments as an array: no shell, no quoting bugs.
  2. The promise rejects on a non-zero exit, carrying stderr.
  3. spawn is the streaming alternative for large output.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Crypto & processes, step 16 of 18 in Node.js.

← Previous Next →