Running Child Commands Safely from Node Build Scripts

A build script which runs another command has acquired a few more responsibilities than its command line suggests. It needs to preserve arguments, choose a working directory, consume output, and decide what counts as success. A filename with a space is quite capable of exposing shortcuts in all of that.
I use Node's spawn() when a command should stream its output whilst it runs. For a local JavaScript tool, I can launch the same Node executable as the parent and pass the script path as an argument. That avoids asking a shell to find and interpret the command for me.
My article on JavaScript build tools and module formats covers the wider tooling context. This example concentrates on the smaller contract between one Node 10 build script and one child command.
Keep the Executable Separate from Its Arguments
The command is an executable path. Arguments belong in an array, with one entry per argument. A path containing spaces remains one entry; it doesn't need quotation marks inserted around it.
With shell: false, shell punctuation in an argument stays argument data. That doesn't make every argument safe for every executable: the target program still interprets its own flags and input. Choose the executable deliberately and validate arguments according to that program's contract.
Avoid solving a quoting problem by enabling a shell around the whole command. That adds another language which must interpret the same strings. Shell features can be useful when they are actually required, but they shouldn't be an accidental dependency of a filename.
The Node 10 child‑process documentation also covers the Windows distinction. Batch files need a suitable command interpreter; they aren't interchangeable with directly executable programs. Launching a JavaScript file through process.execPath avoids that particular wrapper.
Fix the Working Directory and Environment
The caller's current directory is not necessarily the directory containing the build script. Set cwd deliberately, and resolve the script and input paths from a known root. Otherwise, the same command can discover different configuration or write output somewhere unexpected depending on where it was launched.
Choose the environment as well. Passing a small explicit object makes dependencies visible and avoids forwarding unrelated application credentials. A real compiler may need additional variables for its toolchain, locale, or operating system; include those intentionally rather than assuming the minimal example fits every command.
This is process configuration, not a sandbox. The child still has the permissions of the account running it. An explicit argument array and environment don't make an untrusted executable safe to run.
Stream Output and Retain Only the Useful Tail
Child output pipes have finite capacity. If the parent doesn't consume them, a sufficiently chatty child can block waiting for space. That is a particularly unhelpful way for a build to become quiet.
The runner below forwards both streams and retains only their final 64 KiB for a result summary. The copy is deliberate: keeping a small slice of a much larger Buffer could retain its larger backing allocation.
Save this as run.js:
const { spawn } = require("child_process");
function run(command, args, options) {
return new Promise((resolve) => {
const child = spawn(command, args, {
cwd: options.cwd,
env: options.env,
shell: false,
stdio: ["ignore", "pipe", "pipe"],
});
const tails = { stdout: Buffer.alloc(0), stderr: Buffer.alloc(0) };
const limit = 64 * 1024;
let processError = null;
let timedOut = false;
let forceTimer;
["stdout", "stderr"].forEach((name) => {
child[name].pipe(process[name], { end: false });
child[name].on("data", (chunk) => {
const combined = Buffer.concat([tails[name], chunk]);
tails[name] = Buffer.from(combined.slice(-limit));
});
});
child.on("error", (error) => {
processError = { code: error.code, message: error.message };
});
const timer = setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
forceTimer = setTimeout(() => child.kill("SIGKILL"), 1000);
}, options.timeoutMs);
child.on("close", (code, signal) => {
clearTimeout(timer);
clearTimeout(forceTimer);
resolve({
code,
signal,
timedOut,
processError,
stdoutTail: tails.stdout.toString("utf8"),
stderrTail: tails.stderr.toString("utf8"),
});
});
});
}Piping forwards output with stream backpressure. The retained tail is separate from that live output, so a long log doesn't require an equally long string in the result object. It is an excerpt, not a complete transcript. Because the limit is in bytes, decoding that excerpt may begin part‑way through a UTF-8 character.
The promise represents the child's completed result. If that wrapper is unfamiliar, my introduction to promises covers the underlying pattern. It doesn't treat every nonzero status as a rejected promise; instead, the caller receives the observed status, signal, process error, and timeout decision together.
Wait for the Right Event
An error event can mean the process couldn't start, such as an executable which doesn't exist. A nonzero exit status means a process ran and reported failure. Those aren't the same diagnosis, even if both should fail the build.
An exit event reports that the process ended, but its standard streams may still be open. The runner resolves on close, after those streams have closed, so the retained diagnostic tail includes their final output.
A signal is another outcome. Don't invent an exit code when Node reports a signal and a null code. Keep both fields, and preserve the timeout flag separately. A child which handles termination by exiting with code zero still exceeded the parent's time budget.
Writing to stderr also isn't an automatic failure. Some tools put warnings or progress there and finish successfully. Decide from the tool's documented contract and actual result, rather than treating the stream name as a verdict.
Call It with a Concrete Fixture
Append this call to run.js:
const path = require('path');
const root = __dirname;
run(process.execPath, [
path.join(root, 'validate.js'),
path.join(root, 'fixtures', 'sample file.txt'),
], {
cwd: root,
env: { LANG: 'C', BUILD_MODE: 'check' },
timeoutMs: 5000,
}).then((result) => {
if (result.processError || result.code !== 0 || result.signal || result.timedOut) {
console.error(result);
process.exitCode = 1;
}
}).catch((error) => {
console.error(error);
process.exitCode = 1;
});Place this small validate.js beside it, and create a text file at fixtures/sample file.txt:
const fs = require('fs');
const filename = process.argv[2];
if (!filename) {
console.error('Missing filename');
process.exitCode = 2;
} else {
const contents = fs.readFileSync(filename, 'utf8');
console.log(`Checked ${contents.length} characters`);
}Run node run.js. The path is passed literally, including its space. Then remove the input file, try a missing executable, and make the fixture return a nonzero status. Keep those cases separate in the assertions; otherwise, a missing tool can masquerade as a successful test of the tool's validation errors.
Make Termination an Explicit Policy
The timeout first requests SIGTERM, then escalates to SIGKILL after one second if close hasn't arrived. Those intervals are example inputs, not recommended budgets for every build. Both timers are cleared when the observed result arrives.
This policy targets the direct child. It doesn't promise to terminate every descendant, and signal behaviour differs on Windows. A descendant which inherits an output handle can also keep that handle open after its parent exits. Process‑tree supervision needs a platform‑specific decision.
Test a child which waits indefinitely, one which ignores the initial termination request, and one which exits cleanly after receiving it. Confirm that the direct fixture process is gone afterwards, whilst retaining the distinct signal and timeout outcomes.
Wrapping Up
I want a failed build step to explain whether the command was missing, the tool rejected its input, a signal ended it, or the parent stopped waiting. Keeping the executable, arguments, output, and termination policy explicit makes those explanations possible.
It also gives the next person the final diagnostic line, which is usually a better starting point than several megabytes of everything which went well beforehand.
Postscript
November 2026: Modern Node versions accept an AbortSignal in spawn() options; support arrived in Node 14.17 and 15.5. That can connect a child to a caller's cancellation signal, but it doesn't establish platform‑independent process‑tree cleanup. I rechecked the runner on Node 22.23.5 and 24.14.0, including large output, missing commands, signals, and timeout escalation. The 2018 API setting is checked against Node 10.13 documentation; execution on that historical runtime remains unverified.