Bird
0
0

Identify the error in this code using fork and how to fix it:

medium📝 Debug Q14 of 15
Node.js - Child Processes
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.
AError because child.js must listen for messages before parent sends.
BNo error; code works fine.
CError because fork requires a callback function.
DError because child.send is not a function.
Step-by-Step Solution
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]
Quick Trick: Child must handle messages before parent sends [OK]
Common Mistakes:
  • Assuming fork needs callback
  • Thinking child.send is undefined
  • Ignoring child.js message listener

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes