Child processes: execFile and spawn
A Node.js program can start another program and read what it prints, which is how a build script calls a compiler and how a tool calls git. node:child_process has two shapes of that call: execFile runs a program and buffers its output into a string, and spawn hands the output over as streams while the child is still running.
The lesson runs a small script with each of them, reads standard output and standard error, and looks at the exit code of a child that exits on purpose and of one that a signal ends. Every child is the same Node.js binary that runs the parent, through process.execPath, so the programs need no compiler and no absolute path in the source.
execFile
execFile(program, args, callback) starts the program without a shell, so an argument with a space or a quote is passed as it is and nothing is expanded. With promisify the call returns a promise of an object with stdout and stderr, which is the shortest way to run something and read its output.
The program asks a child to print six times seven, then starts a second child with two arguments after the script and prints how many entries the child found in its own argv.
The file execfile.mjs:
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
const run = promisify(execFile);
const { stdout } = await run(process.execPath, ['-e', 'console.log(6 * 7);']);
console.log('the child printed:', stdout.trim());
console.log('stdout is a string:', typeof stdout);
const second = await run(process.execPath, ['-e', 'console.log(process.argv.length);', 'a', 'b']);
console.log('a child with arguments got:', second.stdout.trim(), 'entries of argv');
node execfile.mjs
the child printed: 42
stdout is a string: string
a child with arguments got: 3 entries of argv
The output arrived as a string with the child's newline at the end, which is why the program trims it before printing. The arguments after -e reached the child as its own command-line arguments, so the count is three: the runtime, the script and a.
spawn
spawn returns the child object at once and lets the program listen to stdout and stderr as streams. The close event fires when the child has ended and its output has been read, and it carries the exit code; exit fires a little earlier and can arrive before the last chunk.
The program starts a child that prints three lines, collects the output in a variable, waits for close and prints the code and the lines.
The file spawn.mjs:
import { spawn } from 'node:child_process';
const child = spawn(process.execPath, [
'-e',
'console.log("one"); console.log("two"); console.log("three");',
]);
let output = '';
child.stdout.on('data', (chunk) => {
output += chunk;
});
const code = await new Promise((resolve, reject) => {
child.on('close', resolve);
child.on('error', reject);
});
const lines = output.trimEnd().split('\n');
console.log('the exit code:', code);
console.log('the number of lines:', lines.length);
console.log('the lines:', lines.join(' / '));
node spawn.mjs
the exit code: 0
the number of lines: 3
the lines: one / two / three
The three lines arrived as chunks that were joined by hand. That is the difference from execFile: a child that prints a gigabyte fills a gigabyte of memory with the buffered call and only a buffer with spawn, where the program can also pass each chunk on to a file or to its own output.
Exit codes and signals
A child that ends normally leaves a code between zero and two hundred and fifty-five, and zero means success by convention. A child that a signal ends has no code at all: the code is null and the signal names the reason. A program that checks only the code treats a killed child as a success, which is a bug worth knowing before it happens.
The program starts one child that exits with three and one that sends itself a SIGTERM, and prints the code and the signal of both.
The file codes.mjs:
import { spawn } from 'node:child_process';
const waitFor = (child) =>
new Promise((resolve) => {
child.on('close', (code, signal) => resolve({ code, signal }));
});
const exited = spawn(process.execPath, ['-e', 'process.exit(3);']);
const first = await waitFor(exited);
console.log('a child that exits with 3:', first.code, first.signal);
const killed = spawn(process.execPath, ['-e', 'process.kill(process.pid, "SIGTERM");']);
const second = await waitFor(killed);
console.log('a child that a signal ends:', second.code, second.signal);
console.log('this program is still running');
node codes.mjs
a child that exits with 3: 3 null
a child that a signal ends: null SIGTERM
this program is still running
The first child reported its code and no signal, the second the other way round, and the parent went on after both. The helper that wraps close in a promise is the shape a script uses when it has to run three programs in a row and stop at the first failure.
Standard error and a failing child
A child that exits with a non-zero code makes the promise of execFile reject, and the error carries the code, the signal and both streams. Standard output and standard error stay apart, so a message meant for a human does not end up in the data a program parses.
The child writes one line to standard error and exits with two. The parent prints the code, the message and the signal from the rejected promise.
The file stderr.mjs:
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
const run = promisify(execFile);
try {
await run(process.execPath, [
'-e',
'console.error("no such option"); process.exit(2);',
]);
} catch (error) {
console.log('the call rejected with code:', error.code);
console.log('the message of the child:', error.stderr.trimEnd());
console.log('the signal was:', error.signal);
}
node stderr.mjs
the call rejected with code: 2
the message of the child: no such option
the signal was: null
The code is the status of the child and the signal is null, because the child chose to end. The parent did not fail: it caught the rejection and printed a report, which is what a tool does when a step of a build fails and the remaining steps still have to be reported. The shell sees the same numbers, which the lesson on Bash explains from the other side.
Exercises
- Run a child that prints two lines and print them as they arrive, by logging inside the data handler. How many chunks does the parent see?
- Make a child exit with seven and print the code from the parent. Which event gives it?
- Run a child that writes to standard error and exits with zero through execFile. Does the promise reject?
- Start two children with spawn at the same time and wait for both. Which one ends first?
- What happens to a child that is still running when the parent ends? Start a child that waits ten seconds and see what the shell reports.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does execFile with promisify give when the child ends?
Answer
An object with stdout and stderr
The call waits for the child and buffers both streams into strings.
-
What does this program print?
import { execFile } from "node:child_process"; import { promisify } from "node:util"; const { stdout } = await promisify(execFile)(process.execPath, ["-e", "console.log(2 + 3);"]); console.log(stdout.trim());Answer
5
The child runs the expression and prints its value, and the parent trims the newline.
-
Which call hands the output over as streams while the child runs?
Answer
spawn
spawn returns the child at once and its stdout is a readable stream.
-
What does this program print?
import { spawn } from "node:child_process"; const child = spawn(process.execPath, ["-e", "process.exit(3);"]); const code = await new Promise((resolve) => child.on("close", resolve)); console.log(code);Answer
3
The close event carries the status the child chose, and three is not success.
-
What does the close event carry?
Answer
The exit code and the signal
The two arguments are the code, or null, and the signal, or null.
-
What does this program print?
import { execFile } from "node:child_process"; import { promisify } from "node:util"; try { await promisify(execFile)(process.execPath, ["-e", "process.exit(2);"]); } catch (error) { console.log(error.code); }Answer
2
A non-zero status rejects the promise, and the code of the error is that status.
-
When does the promise of execFile reject?
Answer
When the child exits with a non-zero code
A status above zero is the signal of a failed step, so the call treats it as an error.
-
What does this program print?
import { spawn } from "node:child_process"; const child = spawn(process.execPath, ["-e", "console.error('bad');"]); let message = ""; child.stderr.on("data", (chunk) => { message += chunk; }); await new Promise((resolve) => child.on("close", resolve)); console.log(message.trim());Answer
bad
Standard error is a stream of its own, and the handler collected what the child wrote.
-
What is process.execPath?
Answer
The path of the Node.js binary that runs the program
It is how a program starts a child of its own runtime without knowing where it is installed.
-
A child that a signal ends reports which exit code?
Answer
null, with the name of the signal
There is no status, so the code is null and the signal says what happened.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev