Bird
Raised Fist0
Node.jsframework~20 mins

fork for Node.js child processes in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

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
Challenge - 5 Problems
🎖️
Node.js Fork Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this Node.js fork example?
Consider this code that uses fork from the child_process module. What will be printed to the console?
Node.js
import { fork } from '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 + ' world');
// });
ASyntaxError: Unexpected token import
BParent received: Hello child world
CNo output, program hangs
DParent received: Hello child
Attempts:
2 left
💡 Hint
Remember that fork creates a child process that can communicate via messages.
📝 Syntax
intermediate
1:30remaining
Which option correctly imports and uses fork in Node.js ES modules?
You want to create a child process using fork in a Node.js ES module. Which code snippet is correct?
A
import { fork } from 'child_process';
const child = fork();
B
const { fork } = require('child_process');
const child = fork('script.js');
C
import fork from 'child_process';
const child = fork('script.js');
D
import { fork } from 'child_process';
const child = fork('script.js');
Attempts:
2 left
💡 Hint
ES modules use import syntax and fork requires a script path.
🔧 Debug
advanced
2:30remaining
Why does this forked child process not receive messages?
Given this parent and child code, why does the child never log the message sent by the parent?
Node.js
/* parent.js */
import { fork } from 'child_process';
const child = fork('./child.js');
child.send('ping');

/* child.js */
console.log('Child started');
process.on('message', (msg) => {
  console.log('Child received:', msg);
});
AThe child process exits immediately before receiving messages
BThe child.js file has a syntax error preventing execution
CThe parent never sends any message
DThe fork call is missing the stdio option to enable IPC
Attempts:
2 left
💡 Hint
Check if the child process stays alive to receive messages.
state_output
advanced
2:00remaining
What is the value of variable 'count' after this forked process communication?
In this example, the parent and child share a variable 'count'. What is the final value of 'count' in the parent after the child sends messages?
Node.js
import { fork } from 'child_process';

let count = 0;
const child = fork('./child.js');

child.on('message', (msg) => {
  if (msg === 'increment') count++;
});

child.send('start');

// child.js
// process.on('message', (msg) => {
//   if (msg === 'start') {
//     process.send('increment');
//     process.send('increment');
//   }
// });
A2
B1
C0
DUndefined
Attempts:
2 left
💡 Hint
The child sends two 'increment' messages, each incrementing count by 1.
🧠 Conceptual
expert
3:00remaining
Which statement about Node.js fork and IPC is true?
Select the correct statement about the behavior of fork and inter-process communication (IPC) in Node.js.
AThe forked child process shares the same memory space as the parent, so variables are shared directly.
BThe fork method can only run JavaScript files located in the same directory as the parent.
CMessages sent via <code>child.send()</code> are serialized and sent asynchronously over IPC channels.
DThe child process automatically inherits all open file descriptors from the parent.
Attempts:
2 left
💡 Hint
Think about how processes communicate and memory isolation.

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

  1. 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.
  2. 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.
  3. Final Answer:

    It creates a new Node.js process to run a separate script. -> Option C
  4. 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

  1. 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');
  2. 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.
  3. Final Answer:

    const { fork } = require('child_process'); -> Option B
  4. 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?
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');
// });
medium
A. No output because child.js is missing
B. Parent received: Hello Child
C. Error: child.send is not a function
D. Parent received: Hello Child from Child

Solution

  1. 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'.
  2. 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'.
  3. Final Answer:

    Parent received: Hello Child from Child -> Option D
  4. Quick Check:

    Message sent and replied correctly = D [OK]
Hint: Child replies with modified message; parent logs it [OK]
Common Mistakes:
  • Assuming child.send is undefined
  • Ignoring message event listeners
  • Thinking output is only 'Hello Child'
4. Identify the error in this code using 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.
medium
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

  1. 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.
  2. Step 2: Fix by adding message listener in child.js

    Child script should have process.on('message', (msg) => { ... }) to handle incoming messages properly.
  3. Final Answer:

    Error because child.js must listen for messages before parent sends. -> Option A
  4. 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

  1. Step 1: Understand parallel execution with fork

    Forking both scripts starts them in parallel. To know when both finish, listen for their 'exit' events.
  2. 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.
  3. Final Answer:

    Fork both scripts, listen for 'exit' events on both, then print after both exit. -> Option A
  4. Quick Check:

    Wait for both exits before printing = B [OK]
Hint: Use 'exit' events on both children to sync completion [OK]
Common Mistakes:
  • Starting second child inside first child's exit
  • Printing before children finish
  • Using exec for parallel child processes