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?
BeginnerAnswer
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 inReal-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.