Because Node.js runs on a single main thread, running expensive CPU tasks (such as video encoding with FFmpeg, executing Python AI models, or generating large PDF reports) inside the main event loop will freeze your server. The child_process module enables Node.js to spin up separate operating system processes, execute external CLI programs, and distribute workloads across multiple processes.
| Method | Spawns Shell? | Data Transmission | Best Use Case |
|---|---|---|---|
spawn(cmd, args) |
No (Direct binary) | Streams (Readable stdout/stderr) | Large data transfers, long-running processes (FFmpeg, git). |
exec(cmd, callback) |
Yes (System Shell) | Buffered (Returned in callback) | Quick shell commands with small text output (e.g. uptime). |
execFile(file, args) |
No (Direct binary) | Buffered (Returned in callback) | Executing executable binaries safely without shell injection. |
fork(modulePath) |
No (Node.js engine) | IPC Message Channel | Offloading heavy JavaScript logic into another Node instance. |
spawn()const { spawn } = require('child_process');
// Run 'git status' command and stream output
const git = spawn('git', ['status', '--short']);
git.stdout.on('data', (chunk) => {
console.log('[Git Output]:', chunk.toString());
});
git.stderr.on('data', (errChunk) => {
console.error('[Git Error]:', errChunk.toString());
});
git.on('close', (exitCode) => {
console.log(`Git process exited with code ${exitCode}`);
});
fork()The fork() method creates an IPC channel between the parent and child Node.js processes:
// computeWorker.js (Child Process)
process.on('message', (taskData) => {
console.log('[Child] Received calculation request for number:', taskData.number);
// Heavy CPU computation
let sum = 0;
for (let i = 0; i < taskData.number; i++) {
sum += i;
}
// Send result back to parent process over IPC
process.send({ result: sum, computedAt: new Date() });
});
// parentServer.js (Main Process)
const { fork } = require('child_process');
const path = require('path');
const worker = fork(path.join(__dirname, 'computeWorker.js'));
// Send message to child
worker.send({ number: 500000000 });
// Receive message from child
worker.on('message', (response) => {
console.log('[Parent] Computation result received from child:', response.result);
});
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
Compare multi-process child processes with worker threads.
Cluster uses child_process.fork under the hood.
Trigger external OS binaries asynchronously.