The node:child_process module enables Node.js to spawn sub-processes, execute external terminal commands, run shell scripts, and communicate with child Node.js instances via Inter-Process Communication (IPC).
exec, spawn, fork)flowchart TD
A["node:child_process"] --> B["exec(): Buffer output string (small commands)"]
A --> C["spawn(): Stream large stdout/stderr chunks continuously"]
A --> D["fork(): Spawn Node.js process with dedicated IPC channel"]
import { spawn, exec, fork } from 'node:child_process';
import { promisify } from 'node:util';
const execAsync = promisify(exec);
// 1. Using exec for quick CLI execution
async function runQuickCommand() {
try {
const { stdout, stderr } = await execAsync('node -v');
console.log('Installed Node Version:', stdout.trim());
} catch (err) {
console.error('Command Execution Failed:', err);
}
}
// 2. Using spawn for continuous stream processing
function runStreamedProcess() {
const ls = spawn('ping', ['127.0.0.1']);
ls.stdout.on('data', (data) => {
console.log(`[Spawn Output]: ${data.toString().trim()}`);
});
ls.stderr.on('data', (data) => {
console.error(`[Spawn Error]: ${data}`);
});
ls.on('close', (code) => {
console.log(`Child process exited with code ${code}`);
});
}
runQuickCommand();
runStreamedProcess();
exec(): exec() buffers complete output in memory (default 1MB maxBuffer); use spawn() when commands produce large outputs to prevent memory overflow crashes.exec(); use spawn() with arguments passed as an array.fork() for Node Background Sub-Processes: Use child_process.fork() when spawning another Node.js script to get a built-in IPC channel (process.send()).Which child process method is best suited for executing a child process that streams a 5GB video processing pipeline?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With