Child processes

Topic 2 of 4 in Performance & scaling7 min readIntermediateFree course

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.

Four ways to start another process. execFile runs a program and collects its output — the safest default for tools like ffmpeg, git and convert. spawn streams input and output as it runs, for long-running commands or large output. exec runs a shell command string, useful for pipes and globs but never with user input. fork starts another Node.js script with a message channel.

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:

JavaScript
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:

JavaScript
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 $(…):

JavaScript
// ✗ 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:

JavaScript
// ✓ 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:

JavaScript
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':

JavaScript
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:

JavaScript
// 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();
});
JavaScript
// 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:

JavaScript
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 ffmpeg processes 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), or spawn(…, { 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.

Exercise

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.

JavaScript
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';

const run = promisify(execFile);

export async function gitInfo() {
  // your code here
}

Summary

  • Child processes run other programs (or Node scripts) separately from your main process.
  • execFile runs a program with an argument array and collects its output — the safe default.
  • spawn streams stdin/stdout/stderr, for long-running commands or large output.
  • exec runs a shell command string — never build it from user input (command injection).
  • fork starts another Node script with a built-in message channel; always set timeouts and handle errors and exit codes.