Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Using fork for Node.js Child Processes
📖 Scenario: You are building a Node.js application that needs to perform a heavy calculation without blocking the main program. To do this, you will create a child process using fork to run the calculation separately.
🎯 Goal: Build a Node.js script that uses fork from the child_process module to run a child process. The child process will send a message back to the parent process when it finishes a task.
📋 What You'll Learn
Create a main script that uses fork to start a child process
Create a child script that sends a message back to the parent process
Set up a message listener in the parent to receive messages from the child
Log the message received from the child process in the parent
💡 Why This Matters
🌍 Real World
Using child processes helps keep Node.js applications responsive by offloading heavy or blocking tasks to separate processes.
💼 Career
Understanding how to use fork and child processes is important for backend developers working with Node.js to build scalable and efficient applications.
Progress0 / 4 steps
1
Create the child process script
Create a file named child.js with a single line that sends the message 'Task complete' to the parent process using process.send().
Node.js
Hint
Use process.send('Task complete') to send a message from the child process to the parent.
2
Import fork in the main script
In a new file named parent.js, import the fork function from the child_process module using const { fork } = require('child_process');.
Node.js
Hint
Use const { fork } = require('child_process'); to import fork.
3
Fork the child process and listen for messages
In parent.js, use fork to start child.js and assign it to a variable named child. Then add a listener on child for the message event that receives a parameter msg.
Node.js
Hint
Use fork('./child.js') to start the child process and child.on('message', (msg) => { ... }) to listen for messages.
4
Log the message received from the child process
Inside the message event listener in parent.js, add a line to log the received msg to the console using console.log(msg);.
Node.js
Hint
Use console.log(msg); to print the message from the child process.
Practice
(1/5)
1. What does the fork method in Node.js do?
easy
A. It merges two running processes into one.
B. It pauses the current process for a set time.
C. It creates a new Node.js process to run a separate script.
D. It stops the current process immediately.
Solution
Step 1: Understand the purpose of fork
The fork method 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 C
Quick Check:
fork creates child process = C [OK]
Hint: Remember: fork means start a new Node.js process [OK]
Common Mistakes:
Thinking fork pauses or merges processes
Confusing fork with setTimeout or kill
Assuming fork runs code in the same process
2. Which of the following is the correct way to import and use fork from the child_process module in Node.js?
easy
A. const fork = require('child_process').fork();
B. const { fork } = require('child_process');
C. import fork from 'child_process';
D. const fork = require('child_process').Fork;
Solution
Step 1: Recall correct import syntax for fork
In Node.js CommonJS, fork is a named export from child_process, so we use destructuring: const { fork } = require('child_process');
Step 2: Analyze each option
const fork = require('child_process').fork(); calls 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.
Final Answer:
const { fork } = require('child_process'); -> Option B
Quick Check:
Destructure fork from child_process = A [OK]
Hint: Use curly braces to import fork: const { fork } = require(...) [OK]
Common Mistakes:
Calling fork() during import
Using ES module import without config
Not destructuring fork from module
3. What will be the output of this Node.js code snippet?
A. Error because child.js must listen for messages before parent sends.
B. No error; code works fine.
C. Error because fork requires a callback function.
D. Error because child.send is not a function.
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 have process.on('message', (msg) => { ... }) to handle incoming messages properly.
Final Answer:
Error because child.js must listen for messages before parent sends. -> Option A
Quick Check:
Child must listen for messages = A [OK]
Hint: Child must handle messages before parent sends [OK]
Common Mistakes:
Assuming fork needs callback
Thinking child.send is undefined
Ignoring child.js message listener
5. You want to run two separate scripts 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?
hard
A. Fork both scripts, listen for 'exit' events on both, then print after both exit.
B. Fork one script, then fork the second inside the first child's 'exit' event.
C. Fork both scripts and print "All done" immediately after forking.
D. Use exec instead of fork to run scripts sequentially.
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 A
Quick Check:
Wait for both exits before printing = B [OK]
Hint: Use 'exit' events on both children to sync completion [OK]