Node.js ยท Chapter 33 of 43

Child Processes Overview

The `child_process` module lets Node.js run other programs or scripts as separate OS processes, useful for tasks like running shell commands or offloading CPU-heavy work.

Key methods include `exec()`, `execFile()`, `spawn()`, and `fork()`, each suited to different use cases.

exec vs spawn

`exec()` buffers the entire output and is good for short commands; `spawn()` streams output incrementally, better for long-running or large-output processes.

fork for Node scripts

`fork()` is a special case of spawn specifically for launching other Node.js scripts, with built-in IPC (inter-process communication).

Example 1 (javascript)
const { exec } = require('child_process');
exec('ls -la', (err, stdout, stderr) => {
  if (err) throw err;
  console.log(stdout);
});
Output
total 24
drwxr-xr-x  ...

exec() runs the shell command and buffers all output before the callback fires.

Example 2 (javascript)
const { spawn } = require('child_process');
const ps = spawn('node', ['--version']);
ps.stdout.on('data', data => console.log(`${data}`));
Output
v20.11.0

spawn() streams output as it's produced, better for large or ongoing output.

Key points

  • child_process runs other programs as separate OS processes.
  • exec() buffers output; spawn() streams it.
  • fork() launches other Node.js scripts with built-in IPC.
  • Useful for CPU-heavy tasks or running shell commands.
๐Ÿ’ก Note: Child processes run in parallel, helping avoid blocking Node's single main thread.

๐Ÿ“ Quick Quiz

1. Which method buffers the entire command output before calling back?

2. Which method is best for streaming large or ongoing output?

3. Which method is specifically for launching other Node.js scripts with IPC?