Node.js Child Processes
Sometimes your Node program needs to run another program: call git, convert an image with ImageMagick, run a Python script, or start a second Node process to do heavy work. The node:child_process module starts and talks to these child processes.
Four ways to start a process
| Function | Uses a shell? | Output delivered | Good for |
|---|---|---|---|
spawn(cmd, args) |
no | as streams, while running | long-running tasks, big output |
execFile(file, args, cb) |
no | buffered, all at once | short commands with arguments |
exec(command, cb) |
yes | buffered, all at once | quick shell one-liners with pipes |
fork(modulePath) |
no | streams + message channel | another Node.js script |
Each has a …Sync variant (spawnSync, execFileSync, execSync) that blocks until the child exits — handy in build scripts, not in servers.
Note: The examples below start
process.execPath— the path of the Node binary that is running right now — with-e "code". That way they work on every operating system without depending on other tools being installed.
execFile: run a command, get its output
execFile collects stdout and stderr into strings and calls you back when the child has finished. With util.promisify you can await it:
const { execFile } = require('node:child_process');
const { promisify } = require('node:util');
const execFileAsync = promisify(execFile);
async function main() {
const { stdout } = await execFileAsync(process.execPath, [
'-e',
'console.log("2 + 3 =", 2 + 3); console.log(process.argv.slice(1));',
'alpha',
'beta',
]);
console.log('Child said:');
console.log(stdout.trim());
}
main();Child said:
2 + 3 = 5
[ 'alpha', 'beta' ]
If the child exits with a non-zero code, the promise rejects with an error that has code, stdout and stderr properties.
spawn: streaming output
spawn returns a ChildProcess object immediately. Its stdout and stderr are readable streams, so you see output as soon as it is produced — essential for commands that run for minutes:
const { spawn } = require('node:child_process');
const child = spawn(process.execPath, [
'-e',
`for (let i = 1; i <= 3; i++) console.log('step ' + i);
console.error('a warning');
process.exit(2);`,
]);
child.stdout.setEncoding('utf8');
let out = '';
let err = '';
child.stdout.on('data', (chunk) => { out += chunk; });
child.stderr.on('data', (chunk) => { err += chunk; });
child.on('close', (code) => {
console.log('stdout:', JSON.stringify(out));
console.log('stderr:', JSON.stringify(err.trim()));
console.log('exit code:', code);
});stdout: "step 1\nstep 2\nstep 3\n"
stderr: "a warning"
exit code: 2
Useful spawn options:
| Option | Effect |
|---|---|
cwd |
working directory for the child |
env |
environment variables (default: a copy of process.env) |
stdio: 'inherit' |
child writes straight to your terminal |
shell: true |
run through a shell (be careful, see below) |
signal |
an AbortSignal to kill the child |
timeout |
kill the child after N milliseconds |
Sending input to a child
A child's stdin is a writable stream. Write to it and end() it when done — here the child upper-cases whatever it receives:
const { spawnSync } = require('node:child_process');
const result = spawnSync(
process.execPath,
['-e', 'process.stdin.on("data", d => process.stdout.write(String(d).toUpperCase()))'],
{ input: 'hello from the parent\n', encoding: 'utf8' },
);
console.log('status:', result.status);
console.log('output:', result.stdout.trim());status: 0
output: HELLO FROM THE PARENT
spawnSync is the synchronous version: it accepts the whole input up front and returns status, stdout and stderr once the child is done.
fork: Node-to-Node messaging
fork() starts another Node script and opens an IPC channel, so the two processes can exchange JavaScript objects with send() and the message event:
const { fork } = require('node:child_process');
const fs = require('node:fs');
fs.writeFileSync('square-worker.js', `
process.on('message', (n) => {
process.send({ n, square: n * n });
if (n === 3) process.disconnect();
});
`);
const child = fork('./square-worker.js');
child.on('message', (msg) => console.log('parent got', msg));
child.on('exit', (code) => {
console.log('worker exited with', code);
fs.unlinkSync('square-worker.js');
});
for (const n of [1, 2, 3]) child.send(n);parent got { n: 1, square: 1 }
parent got { n: 2, square: 4 }
parent got { n: 3, square: 9 }
worker exited with 0
Security: avoid the shell with user input
exec() passes a single string to /bin/sh (or cmd.exe). If part of that string comes from a user, they can inject extra commands:
// DANGEROUS: filename = "x; rm -rf ~"
exec(`cat ${filename}`, callback);
// SAFE: arguments are passed directly, never interpreted by a shell
execFile('cat', [filename], callback);Tip: Prefer
spawn/execFilewith an argument array. Only useexecorshell: truefor fixed command strings you wrote yourself.
Test yourself
Which function streams a child's output while it is still running?
- exec
- execFile
- spawn
- execSync
What does fork() add compared to spawn()?
- A shell
- An IPC channel for
send()/message - Automatic retries
- Synchronous execution
Why is exec(cat ${userInput}) risky?
- It is slow
- The shell may run commands injected through the input
- It can't read files
- It only works on Windows