🔹 What Are Child Processes?
Node.js runs on a single thread, which means it can handle one task at a time. To run multiple tasks in parallel or perform CPU-heavy work, Node.js allows you to create child processes. These are separate processes that can run independently but are connected to the main Node.js process.
⚡ spawn: Real-Time Streaming
The spawn method is used when you want to run a command and get output in real-time.
Simple Points
- Streams output line by line.
- Efficient for large or continuous outputs.
- Doesn’t store everything in memory at once.
Example
const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
console.log(`Output: ${data}`);
});
ls.stderr.on('data', (data) => {
console.error(`Error: ${data}`);
});
ls.on('close', (code) => {
console.log(`Process exited with code ${code}`);
});
Output comes as a stream, so large data doesn’t crash your app.
⚡ exec: Buffered Output
The exec method runs a command and gives the entire output at once.
Simple Points
- Best for short commands with small outputs.
- Stores the full output in memory (can crash if the output is too big).
- Simple syntax for getting the result after the command completes.
Example
const { exec } = require('child_process');
exec('ls -lh /usr', (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error.message}`);
return;
}
if (stderr) {
console.error(`Stderr: ${stderr}`);
return;
}
console.log(`Output:
${stdout}`);
});
You get the full command output once it finishes, suitable for quick commands.
⚡ fork: Node.js-Specific Child Process
The fork method is used only for Node.js scripts. It allows parent and child processes to communicate via messages.
Simple Points
- Runs a Node.js module as a child process.
- Allows easy message passing between parent and child.
- Useful for parallel processing in Node.js apps.
Example
// parent.js
const { fork } = require('child_process');
const child = fork('child.js');
child.send({ message: 'Hello Child!' });
child.on('message', (msg) => {
console.log('Message from child:', msg);
});
// child.js
process.on('message', (msg) => {
console.log('Message from parent:', msg);
process.send({ message: 'Hello Parent!' });
});
The parent and child can send messages back and forth, making it great for distributing work.
📊 Key Differences
Method |
Output Type |
Best Use |
Communication |
spawn |
Stream |
Large or continuous output |
None by default |
exec |
Buffer |
Small commands, short output |
None |
fork |
Node.js module |
Parallel Node.js tasks |
Built-in messaging |
📝 Summary
In Node.js, spawn, exec, and fork are used to create child processes. spawn is best for large, real-time outputs; exec is simple and suitable for small command outputs; and fork is specifically designed for Node.js scripts with message passing. Understanding these differences helps developers choose the right method to efficiently run parallel tasks and manage resources.