Fork lets you run another Node.js script as a separate process. This helps your app do many things at once without slowing down.
fork for Node.js child processes in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
import { fork } from 'child_process'; const child = fork('script.js', ['arg1', 'arg2'], { cwd: '/path/to/dir', env: { ...process.env, CUSTOM_VAR: 'value' }, silent: false });
The first argument is the path to the script you want to run.
You can pass arguments as an array to the child script.
worker.js as a child process with no extra arguments.import { fork } from 'child_process'; const child = fork('worker.js');
worker.js which it can access via process.argv.import { fork } from 'child_process'; const child = fork('worker.js', ['task1', 'task2']);
import { fork } from 'child_process'; const child = fork('worker.js', [], { silent: true });
This example shows how to fork a child process running worker.js. The parent sends a message to start a task. The child listens for this message and replies back. This way, both processes talk to each other without blocking.
import { fork } from 'child_process'; // Fork a child process to run worker.js const child = fork('./worker.js'); // Listen for messages from the child child.on('message', (msg) => { console.log('Message from child:', msg); }); // Send a message to the child child.send({ task: 'start' }); // worker.js content: // process.on('message', (msg) => { // if (msg.task === 'start') { // process.send('Task started'); // } // });
Child processes run independently but can communicate using messages.
Use child.send() and process.on('message') to talk between parent and child.
Remember to handle errors and exit events to avoid zombie processes.
fork runs another Node.js script as a separate process.
It helps keep your app fast by doing work in parallel.
You can send messages back and forth between parent and child.
Practice
fork method in Node.js do?Solution
Step 1: Understand the purpose of
Theforkforkmethod is used to create a new child process that runs a separate Node.js script independently.Step 2: Compare options with the definition
Only It creates a new Node.js process to run a separate script. correctly describes this behavior. Other options describe unrelated actions like pausing, merging, or stopping processes.Final Answer:
It creates a new Node.js process to run a separate script. -> Option CQuick Check:
forkcreates child process = C [OK]
- Thinking fork pauses or merges processes
- Confusing fork with setTimeout or kill
- Assuming fork runs code in the same process
fork from the child_process module in Node.js?Solution
Step 1: Recall correct import syntax for fork
In Node.js CommonJS,forkis a named export fromchild_process, so we use destructuring:const { fork } = require('child_process');Step 2: Analyze each option
const fork = require('child_process').fork(); callsfork()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.Final Answer:
const { fork } = require('child_process'); -> Option BQuick Check:
Destructure fork from child_process = A [OK]
- Calling fork() during import
- Using ES module import without config
- Not destructuring fork from module
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');
// });Solution
Step 1: Understand message passing between parent and child
The parent sends 'Hello Child' to the child process. The child listens for messages and replies by appending ' from Child'.Step 2: Trace the output
The parent listens for messages from the child and logs them. So it logs: 'Parent received: Hello Child from Child'.Final Answer:
Parent received: Hello Child from Child -> Option DQuick Check:
Message sent and replied correctly = D [OK]
- Assuming child.send is undefined
- Ignoring message event listeners
- Thinking output is only 'Hello 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.Solution
Step 1: Check message handling in child.js
If child.js does not listen for messages, sending messages from parent has no effect and may cause unexpected behavior.Step 2: Fix by adding message listener in child.js
Child script should haveprocess.on('message', (msg) => { ... })to handle incoming messages properly.Final Answer:
Error because child.js must listen for messages before parent sends. -> Option AQuick Check:
Child must listen for messages = A [OK]
- Assuming fork needs callback
- Thinking child.send is undefined
- Ignoring child.js message listener
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?Solution
Step 1: Understand parallel execution with fork
Forking both scripts starts them in parallel. To know when both finish, listen for their 'exit' events.Step 2: Wait for both exit events before printing
Track both exits with counters or flags, then print "All done" only after both have exited.Final Answer:
Fork both scripts, listen for 'exit' events on both, then print after both exit. -> Option AQuick Check:
Wait for both exits before printing = B [OK]
- Starting second child inside first child's exit
- Printing before children finish
- Using exec for parallel child processes
