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).
const { exec } = require('child_process');
exec('ls -la', (err, stdout, stderr) => {
if (err) throw err;
console.log(stdout);
});total 24
drwxr-xr-x ...exec() runs the shell command and buffers all output before the callback fires.
const { spawn } = require('child_process');
const ps = spawn('node', ['--version']);
ps.stdout.on('data', data => console.log(`${data}`));v20.11.0spawn() 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.
