Node.js Child Processes - Mastering spawn, exec, execFile & fork for OS Execution

Because Node.js runs on a single main thread, running expensive CPU tasks (such as video encoding with FFmpeg, executing Python AI models, or generating large PDF reports) inside the main event loop will freeze your server. The child_process module enables Node.js to spin up separate operating system processes, execute external CLI programs, and distribute workloads across multiple processes.

Cluster Module vs Worker Threads in Node.js Architecture
Figure 7: Process-Level Isolation (Cluster & Child Processes) vs In-Memory Multi-Threading (Worker Threads)

The Four Child Process Creation Methods

Method Spawns Shell? Data Transmission Best Use Case
spawn(cmd, args) No (Direct binary) Streams (Readable stdout/stderr) Large data transfers, long-running processes (FFmpeg, git).
exec(cmd, callback) Yes (System Shell) Buffered (Returned in callback) Quick shell commands with small text output (e.g. uptime).
execFile(file, args) No (Direct binary) Buffered (Returned in callback) Executing executable binaries safely without shell injection.
fork(modulePath) No (Node.js engine) IPC Message Channel Offloading heavy JavaScript logic into another Node instance.

1. Streaming Command Output with spawn()

const { spawn } = require('child_process');

// Run 'git status' command and stream output
const git = spawn('git', ['status', '--short']);

git.stdout.on('data', (chunk) => {
  console.log('[Git Output]:', chunk.toString());
});

git.stderr.on('data', (errChunk) => {
  console.error('[Git Error]:', errChunk.toString());
});

git.on('close', (exitCode) => {
  console.log(`Git process exited with code ${exitCode}`);
});

2. Two-Way IPC Communication with fork()

The fork() method creates an IPC channel between the parent and child Node.js processes:

// computeWorker.js (Child Process)
process.on('message', (taskData) => {
  console.log('[Child] Received calculation request for number:', taskData.number);

  // Heavy CPU computation
  let sum = 0;
  for (let i = 0; i < taskData.number; i++) {
    sum += i;
  }

  // Send result back to parent process over IPC
  process.send({ result: sum, computedAt: new Date() });
});
// parentServer.js (Main Process)
const { fork } = require('child_process');
const path = require('path');

const worker = fork(path.join(__dirname, 'computeWorker.js'));

// Send message to child
worker.send({ number: 500000000 });

// Receive message from child
worker.on('message', (response) => {
  console.log('[Parent] Computation result received from child:', response.result);
});

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the difference between spawn() and exec() in child_process?

exec() buffers the entire output of the command in memory before passing it to a callback (default 1MB buffer limit, which can throw ERR_CHILD_PROCESS_STDIO_MAXBUFFER). spawn() streams output chunks continuously via stdout/stderr Readable streams, making it suitable for commands with massive output or long-running processes.

Q2. What does child_process.fork() do and how does IPC work?

fork() is a specialized variant of spawn() designed exclusively to launch new Node.js instances. It establishes a dedicated Inter-Process Communication (IPC) channel, allowing parent and child processes to exchange structured JavaScript objects using 'child.send()' and 'process.on("message", ...)'.

Q3. Why is exec() vulnerable to Command Injection and how do you protect against it?

exec() passes commands through a shell (like /bin/sh or cmd.exe). If user input is concatenated into the command, attackers can append shell delimiters (e.g. '; rm -rf /'). Use execFile() or spawn() instead, which do NOT invoke a shell and pass arguments as an isolated string array.

Explore Related Node.js Tutorials & Next Steps

Boost your server-side JavaScript proficiency by studying these closely connected core modules:

Worker Threads & CPU Offloading

Compare multi-process child processes with worker threads.

Cluster Module & Multi-Core

Cluster uses child_process.fork under the hood.

Task Scheduling & Cron Jobs

Trigger external OS binaries asynchronously.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!