Node.js › Child Processes & Process Management

What are the four main methods for creating a child process in Node.js, and how do they differ?

Beginner

Answer

spawn() launches a command and streams its stdout/stderr incrementally, suited for long-running processes or large output. exec() runs a command through a shell and buffers its entire output into a callback, convenient for short commands with small output but risky for large output (memory) and shell-injection if input isn't sanitized. execFile() is like exec() but runs an executable directly without a shell, avoiding shell-injection risk. fork() is a specialized spawn specifically for running another Node.js script as a child process, automatically setting up an IPC channel for message passing.
const { spawn, exec, execFile, fork } = require('node:child_process');

spawn('ls', ['-la']); // streaming output
exec('ls -la', (err, stdout) => console.log(stdout)); // buffered, via shell
execFile('ls', ['-la'], (err, stdout) => console.log(stdout)); // buffered, no shell
fork('./worker-script.js'); // another Node.js process, with IPC built in
Real-world example A CI tool uses spawn() to stream a long-running build command's output line by line to the console in real time, while a smaller utility script uses execFile() to safely run a fixed executable with user-supplied arguments, avoiding the shell-injection risk that exec() would introduce with unsanitized input.

Common follow-ups: Why is exec() considered risky when any part of the command string comes from user input?;What's the memory implication of exec()'s output-buffering behavior for a command producing gigabytes of output?