Performance: Why child processes are needed
This concept affects how Node.js handles CPU-intensive tasks and parallel work, impacting responsiveness and throughput.
Jump into concepts and practice - no test required
import { fork } from 'child_process'; const child = fork('heavyTask.js'); child.on('message', msg => console.log(msg));
const heavyTask = () => { while(true) {} }; heavyTask();| Pattern | CPU Blocking | Event Loop Delay | Memory Overhead | Verdict |
|---|---|---|---|---|
| Synchronous heavy task in main process | Blocks CPU fully | Blocks event loop causing high INP | Low memory but poor responsiveness | [X] Bad |
| Heavy task in child process | Runs in parallel CPU | Event loop remains free, low INP | Higher memory due to extra process | [OK] Good |
const { fork } = require('child_process');
const child = fork('child.js');
child.on('message', (msg) => {
console.log('Message from child:', msg);
});
child.send('Hello');child.js sends back the message { reply: 'Hi' } when it receives a message.const { fork } = require('child_process');
const child = fork('worker.js');
child.send('start');
child.on('message', (msg) => {
console.log(msg);
});
child.on('error', (err) => {
console.error('Child error:', err);
});