Child Processes and Cluster
Node.js can create child processes to execute other programs or isolate work. The cluster module can create multiple Node.js processes that share a server port, allowing applications to utilize multiple CPU cores.
Modern production deployments frequently use external process managers or container orchestration instead of relying exclusively on Node's built-in clustering features.
Running a Child Process
import { execFile } from 'node:child_process';
execFile('node', ['--version'], (error, stdout, stderr) => {
if (error) {
console.error(error);
return;
}
console.log(stdout.trim());
});💡
execFile() runs an executable with an argument array, avoiding the shell parsing behavior of exec().Key Takeaways
- Child processes provide process-level isolation and can execute external programs.
- Cluster uses multiple Node.js processes rather than multiple JavaScript threads.
- Production architecture should consider containers and orchestration as well.
Knowledge Check
What is a key distinction between Worker Threads and cluster processes?