Child processes
Run other programs from Node with spawn, execFile, exec and fork, stream their output, talk to Node children over IPC, and avoid shell injection.
Child processes
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `child_process` starts a separate OS process with its own memory and its own event loop. A crash or a heavy computation there does not block or kill the parent.
- `spawn(cmd, args)` streams stdout and stderr as it runs and is the right tool for long output. `execFile` and `exec` buffer the whole output and hand it to a callback, with a `maxBuffer` limit.
- `exec` runs through a shell, so interpolating user input into the command string is shell injection. `execFile` and `spawn` take an argument array and no shell by default.
- `fork(file)` starts another Node script and opens an IPC channel, so `child.send(obj)` and `process.on('message')` work in both directions.
- Check both `error` (the process could not start, for example ENOENT) and `close` (exit code and signal). A non-zero exit code is not an `error` event.
Why start another process
Sometimes the best tool is not JavaScript: ffmpeg for video, git, pandoc, a Python script. Sometimes you want isolation: run risky or CPU-heavy work in a separate process so a crash or a long computation cannot take your server with it. Node’s child_process module covers both. The child is a full OS process with its own memory and its own event loop. If you want parallelism within one process sharing memory, see worker threads.
Four functions, one real distinction
| Function | Shell? | Output | Use for |
|---|---|---|---|
spawn(cmd, args) |
no | streams | long-running or large output |
execFile(cmd, args) |
no | buffered, callback/promise | short commands, small output |
exec(cmdString) |
yes | buffered | shell features, trusted strings only |
fork(script) |
no | IPC messages | other Node scripts |
They differ on two axes: whether the output is streamed or buffered, and whether a shell is involved.
spawn: streaming
import { spawn } from 'node:child_process';
const child = spawn('node', ['-e', 'console.log("out1"); console.error("err1"); setTimeout(() => process.exit(3), 20)']);
child.stdout.on('data', (d) => console.log('stdout:', d.toString().trim()));
child.stderr.on('data', (d) => console.log('stderr:', d.toString().trim()));
child.on('close', (code, signal) => console.log('close', code, signal)); // close 3 null
child.stdout and child.stderr are Readable streams, so everything from the streams lessons, including pipeline, applies, and child.stdin is Writable. Two events matter. close fires after the process exits and its streams have closed, with the exit code or the signal that killed it. error fires when the process could not be started:
spawn('definitely-not-a-cmd').on('error', (e) => console.log(e.code)); // ENOENT
A non-zero exit is not an error event. Check code yourself. A missing error listener on a failed spawn throws, which is a common way to crash a service.
execFile and exec: buffered
When the output is small and you just want the result, use the promise form:
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
const execFileP = promisify(execFile);
const { stdout } = await execFileP('node', ['-p', '"a b".split(" ").length']);
console.log(stdout.trim()); // 2
await execFileP('node', ['-e', 'process.exit(2)']).catch((e) => console.log(e.code)); // 2
Here a non-zero exit does reject, with the exit code on err.code. Output beyond maxBuffer (1 MiB by default for exec and execFile in current Node) kills the child and rejects with ERR_CHILD_PROCESS_STDIO_MAXBUFFER. Reach for spawn when output could be big.
The shell injection trap
exec hands a string to /bin/sh. If any part of that string comes from a user, they can add commands:
const name = 'x; echo INJECTED';
exec(`echo hello ${name}`, (err, out) => console.log(JSON.stringify(out)));
// "hello x\nINJECTED\n" -- the second command ran
const safe = await execFileP('echo', ['hello', name]);
console.log(JSON.stringify(safe.stdout));
// "hello x; echo INJECTED\n" -- treated as one literal argument
Both ran on Node 26 as written. The rule: pass arguments as an array to execFile or spawn, and keep exec and { shell: true } for fixed strings you wrote. See input validation and injection for the general principle.
fork and IPC
fork starts another Node script and connects a message channel:
// parent.mjs
import { fork } from 'node:child_process';
const child = fork('./child.mjs');
child.on('message', (m) => console.log('parent got', m));
child.send({ hello: 1 });
child.send('bye');
// child.mjs
process.on('message', (m) => {
process.send({ got: m });
if (m === 'bye') process.disconnect();
});
Messages are serialised, so you can send objects but not functions. It is the building block behind cluster. Options worth knowing: timeout (the child gets SIGTERM after that many ms; I saw [ null, 'SIGTERM' ] for a 50 ms timeout), cwd, env, and signal for cancellation.
What the video covers
Software Developer Diaries’ April 2024 video describes the Child Process module as a way to spin up new, isolated processes, and says it is similar to Worker Threads in usage but differs in purpose. I could not read a transcript, so I can’t say which functions it demos. Treat the table, the error versus close distinction, the buffer limit and the injection example here as this page’s own, run on Node 26.
Where this fits
Child processes are one of three ways to use more than one CPU core: separate processes here, shared-memory threads in worker threads, and many copies of a server in cluster. They also underlie building CLI tools.
Check yourself
You need to run `git log` on a repository with a 400 MB history and process each line. Which function?
`spawn('git', ['log'])` and read `child.stdout` as a stream, ideally through `readline`. `exec` and `execFile` collect everything into one string first and fail with `ERR_CHILD_PROCESS_STDIO_MAXBUFFER` once output passes `maxBuffer`.
Why is `exec(`convert ${filename} out.png`)` a security problem?
The string goes to a shell. A filename like `x; rm -rf ~` or one with `$(...)` runs extra commands. Use `execFile('convert', [filename, 'out.png'])`, which passes arguments directly and never invokes a shell. In a test, `exec('echo hello x; echo INJECTED')` printed the injected output, while `execFile('echo', ['hello', 'x; echo INJECTED'])` printed the text literally.
A spawned command does not exist. Where does the failure show up?
As an `error` event on the ChildProcess with `code: 'ENOENT'`, not an exit code. If you attach no `error` listener, the event throws and can crash the process. A command that starts but exits non-zero reports through `close` or `exit` with the code.
How is `fork` different from `spawn('node', ['script.js'])`?
`fork` is built for Node children. It starts the same Node binary and sets up an IPC channel for structured messages with `send` and `message`, so you can pass objects instead of bytes. A plain `spawn` has no such channel.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.