Node.js theorytheory 0/50 · 0%
Foundations · easy

19. Child processes

Running external programs and other Node scripts from Node.

`node:child_process` lets a Node script launch other programs: `exec`/`execFile` (buffer all output, callback-based), `spawn` (streams output incrementally, best for long-running or large-output processes), and `fork` (spawns another Node.js process with a built-in IPC channel).

js
import { spawn } from "node:child_process";

const child = spawn("node", ["--version"]);
child.stdout.on("data", (chunk) => console.log("stdout:", chunk.toString()));
child.on("close", (code) => console.log("exited with", code));

`fork` is the pattern used to offload CPU-heavy work (e.g. verifying signatures in bulk) to a separate process while the main process keeps serving requests, communicating via `process.send`/`on("message")`.

Check your understanding

  1. 1. Which method streams a child process's output incrementally instead of buffering it all?

  2. 2. What does fork specifically create?

  3. 3. Why offload CPU-heavy work to a child process?