A child process is a separate process created by your main Node.js application (called the parent process). These child processes can execute system commands like listing files, running Python scripts, or even launching another Node.js script [[2]].
This is super useful when:
- You need to run shell commands from your app.
- You want to execute another program outside of Node.js.
- You’re building tools that interact with the operating system.
How to Create a Child Process in Node.js
Node.js provides a built-in module called child_process
for this purpose. There are two main ways to create a child process:
spawn()
– for long-running processes.exec()
– for short tasks where you just need the result.
Let’s look at both with easy examples.
✅ Example 1: Using spawn()
to List Files
const { spawn } = require('child_process');
// On Windows? Use 'dir' instead of 'ls'
const ls = spawn('ls', ['-la']);
ls.stdout.on('data', (data) => {
console.log(`Output:\n${data}`);
});
ls.stderr.on('data', (data) => {
console.error(`Error:\n${data}`);
});
ls.on('close', (code) => {
console.log(`Child process exited with code ${code}`);
});
📌 This example uses spawn()
to list all files in the current directory. It listens for output and errors and tells you when the process ends [[4]].
✅ Example 2: Using exec()
to Run a Command
const { exec } = require('child_process');
exec('echo Hello from the command line!', (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error.message}`);
return;
}
if (stderr) {
console.error(`Stderr: ${stderr}`);
return;
}
console.log(`Output: ${stdout}`);
});
📌 This example runs a simple command (echo
) and logs the output. It’s great for small tasks [[1]].
When Should You Use fork()
?
There’s also a method called fork()
, which is a special version of spawn()
designed specifically for running other Node.js scripts.
✅ Example 3: Using fork()
to Run Another Node Script
Create a file called worker.js
:
console.log('Worker process started');
setTimeout(() => {
console.log('Worker is doing something...');
}, 2000);
Now, in your main file:
const { fork } = require('child_process');
const worker = fork('worker.js');
worker.on('message', (msg) => {
console.log('Message from worker:', msg);
});
worker.on('exit', (code) => {
console.log(`Worker process exited with code ${code}`);
});
📌 fork()
is perfect when you want to run another Node.js file independently [[6]].
Why Use Child Processes?
- Run system commands from inside your app.
- Separate memory space – each child process has its own memory [[8]].
- Better performance – offload heavy tasks to child processes.
Summary
Method | Use Case |
---|---|
spawn() | Long-running commands or streaming output |
exec() | Short commands where you just need the result |
fork() | Run other Node.js scripts |
Final Thoughts
Understanding child processes gives you more control over how your application interacts with the system. Whether it’s executing shell commands, running background jobs, or managing multiple Node.js scripts, the child_process
module is your go-to tool [[9]].
🚀 Ready to start using child processes in your Node.js apps? Try the examples above and see the power for yourself!