Child processes
Overview
Sometimes the best tool for a job isn’t JavaScript: ffmpeg for video, ImageMagick or libvips for images, git, pg_dump for backups, a Python script for machine learning, or a system command. Node’s child_process module lets your program start other programs, feed them input and read their output.
Child processes also give you isolation: if the other program crashes or uses a lot of memory, your Node process is unaffected.
execFile — the safe default
execFile runs a program directly (no shell) with an array of arguments, waits for it to finish, and gives you its output:
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
const run = promisify(execFile);
const { stdout } = await run('git', ['log', '-1', '--format=%H %s'], { timeout: 5000 });
console.log(stdout.trim());If the program exits with a non-zero code, the promise rejects; the error has code, stdout and stderr:
try {
await run('ffmpeg', ['-i', input, '-vf', 'scale=640:-1', output], { timeout: 60_000 });
} catch (err) {
console.error(`ffmpeg failed (exit ${err.code}):`, err.stderr);
throw new Error('Video conversion failed', { cause: err });
}Useful options: cwd (working directory), env (environment variables), timeout (kill after N ms), maxBuffer (output size limit, 1 MB by default) and signal (an AbortSignal).
Command injection
The most important rule of this topic. exec runs a command string through a shell, so the shell interprets spaces, quotes, ;, |, && and $(…):
// ✗ DANGEROUS
exec(`convert uploads/${req.body.filename} -resize 200x200 thumbs/out.png`);
// filename = "x.png; rm -rf / #" → the shell runs rm -rf /With execFile and an argument array, each argument goes to the program as is — no shell, no interpretation:
// ✓ Safe: 'x.png; rm -rf / #' is just a strange (non-existent) file name
await run('convert', [path.join('uploads', safeName), '-resize', '200x200', 'thumbs/out.png']);Still validate inputs (and resolve paths safely), but execFile removes the shell from the equation. Use exec only for fixed commands you write yourself, when you genuinely need shell features like pipes.
spawn — streaming output
execFile buffers all output in memory until the program exits. For long-running programs or large output, spawn gives you streams as the program runs:
import { spawn } from 'node:child_process';
import { createWriteStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';
import { once } from 'node:events';
const dump = spawn('pg_dump', ['--format=custom', process.env.DATABASE_URL]);
await Promise.all([
pipeline(dump.stdout, createWriteStream('backup.dump')),
once(dump, 'close').then(([code]) => {
if (code !== 0) throw new Error(`pg_dump exited with ${code}`);
}),
]);The child’s stdout and stderr are readable streams, and stdin is writable — so you can pipe data into a program and stream its output straight into a file or an HTTP response.
To show a child’s output in your own terminal, use stdio: 'inherit':
spawn('npm', ['run', 'build'], { stdio: 'inherit' });fork — Node talking to Node
fork starts another Node.js script with a built-in message channel, similar to worker threads but as a full separate process:
// parent.js
import { fork } from 'node:child_process';
const child = fork(new URL('./resize-child.js', import.meta.url));
child.send({ file: 'photo.jpg', width: 800 });
child.on('message', (result) => {
console.log('resized:', result);
child.disconnect();
});// resize-child.js
process.on('message', async (job) => {
const result = await resize(job.file, job.width);
process.send(result);
});Processes are heavier than worker threads but fully isolated — a crash or memory leak in the child can’t affect the parent. That’s useful for running untrusted or unstable work.
Handling exits and errors
A child process can fail in several ways; handle them all:
const child = spawn('some-tool', args);
child.on('error', (err) => {
// the program couldn't be started at all — e.g. ENOENT: not installed
});
child.on('exit', (code, signal) => {
// code: exit status (0 = success); signal: e.g. 'SIGTERM' if it was killed
});- Always set a timeout (or an
AbortSignal), so a hung program doesn’t hang your request forever. - Limit concurrency — starting fifty
ffmpegprocesses at once will grind the machine to a halt. A job queue with a concurrency limit is ideal for this kind of work. - Clean up — if your server shuts down, kill the children it started.
Cross-platform notes
- Program names differ: on Windows, many tools need their extension (
npm.cmd), orspawn(…, { shell: true })— which brings back the shell, so only use it with fixed arguments. - Make sure the programs you call exist in your production image. If you use
ffmpeg, install it in your Dockerfile.
Choose by need: collect output →
execFile; stream output →spawn; talk to another Node script →fork(or worker threads); shell features with fixed text only →exec.
Read the current Git commit
Write gitInfo() that uses execFile (promisified) to run git rev-parse --short HEAD and git branch --show-current, returning { commit, branch }. Give each call a 2-second timeout, and return null if Git isn't available or this isn't a repository.
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
const run = promisify(execFile);
export async function gitInfo() {
// your code here
}import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
const run = promisify(execFile);
export async function gitInfo() {
try {
const [commit, branch] = await Promise.all([
run('git', ['rev-parse', '--short', 'HEAD'], { timeout: 2000 }),
run('git', ['branch', '--show-current'], { timeout: 2000 }),
]);
return { commit: commit.stdout.trim(), branch: branch.stdout.trim() };
} catch {
return null;
}
}Summary
- Child processes run other programs (or Node scripts) separately from your main process.
execFileruns a program with an argument array and collects its output — the safe default.spawnstreams stdin/stdout/stderr, for long-running commands or large output.execruns a shell command string — never build it from user input (command injection).forkstarts another Node script with a built-in message channel; always set timeouts and handle errors and exit codes.