Performance: fork for Node.js child processes
This affects how Node.js handles parallel tasks and CPU-intensive operations without blocking the main event loop.
Jump into concepts and practice - no test required
const { fork } = require('child_process');
const child = fork('heavyTask.js');
child.on('message', (result) => {
console.log(result);
});
child.send('start');const result = heavyComputation(); // runs in main process synchronously
console.log(result);| Pattern | CPU Usage | Event Loop Blocking | IPC Overhead | Verdict |
|---|---|---|---|---|
| Synchronous heavy task in main process | High CPU on main thread | Blocks event loop fully | None | [X] Bad |
| Using forked child process for heavy task | Distributed CPU load | No blocking on main thread | Moderate IPC overhead | [OK] Good |
fork method in Node.js do?forkfork method is used to create a new child process that runs a separate Node.js script independently.fork creates child process = C [OK]fork from the child_process module in Node.js?fork is a named export from child_process, so we use destructuring: const { fork } = require('child_process');fork() immediately, which is incorrect. import fork from 'child_process'; uses ES module syntax without proper setup. const fork = require('child_process').fork; assigns the function but misses destructuring. const { fork } = require('child_process'); is correct.const { fork } = require('child_process');
const child = fork('child.js');
child.on('message', (msg) => {
console.log('Parent received:', msg);
});
child.send('Hello Child');
// child.js content:
// process.on('message', (msg) => {
// process.send(msg + ' from Child');
// });fork and how to fix it:
const { fork } = require('child_process');
const child = fork('child.js');
child.send('start');
child.on('message', (msg) => {
console.log(msg);
});
Assuming child.js does not listen for messages.process.on('message', (msg) => { ... }) to handle incoming messages properly.worker1.js and worker2.js in parallel using fork. You also want to collect their results and print "All done" only after both finish. Which approach correctly achieves this?