NodeJS by Example: Child Processes
|
The Child Process module lets you spawn new processes, execute commands, and communicate with them. It's essential for running system commands and parallel processing. |
|
|
Import the child process functions |
|
|
exec() - Run Shell Commands exec() runs a command in a shell and buffers the output. Best for simple commands with small output. |
|
|
exec() with Promises Use the promisified version for async/await. |
|
|
spawn() - Stream Output spawn() launches a process and provides streams for I/O. Best for long-running processes or large output. |
|
|
spawn() with Options Configure the spawned process with options. |
|
|
Inheriting stdio Pass 'inherit' to connect child's stdio to parent's. |
|
|
execFile() - Run Executables execFile() runs an executable directly without a shell. More secure for untrusted input. |
|
|
fork() - Spawn Node.js Processes fork() is specialized for spawning Node.js processes with built-in IPC channel. In parent process: const child = fork('./worker.js'); Send message to child child.send({ type: 'task', data: [1, 2, 3] }); Receive messages from child child.on('message', (message) => { console.log('From child:', message); }); |
|
|
Inter-Process Communication (IPC) Communicate between parent and child processes. |
|
|
Killing Processes Terminate child processes when needed. |
|
|
Handling Errors Handle spawn errors (command not found, permission denied, etc.). |
|
|
Detached Processes Create processes that can outlive the parent. |
|
|
Piping Between Processes Connect multiple processes together. |
|
|
Writing to stdin Send input to a child process. |
|
|
Practical Example: Command Runner A utility for running commands with timeout and output capture. Usage |
|
|
Practical Example: Parallel Task Runner Run multiple commands in parallel with concurrency limit. Usage runParallel(['echo 1', 'echo 2', 'echo 3'], 2).then(console.log); |
|
|
Run the child processes example |
|