Bird
0
0

Examine this Node.js code snippet:

medium📝 Debug Q7 of 15
Node.js - Child Processes
Examine this Node.js code snippet:
const { fork } = require('child_process');
const child = fork('worker.js');
child.send('start');
child.on('message', msg => console.log(msg));
child.on('error', err => console.log('Error:', err));
child.on('exit', code => console.log('Exited with', code));

What is the issue with this code?
AThe 'send' method cannot be used with forked processes
BThe 'error' event listener is incorrectly implemented
CThe 'exit' event should be replaced with 'close' event
DThe child process may not be ready to receive messages immediately after fork
Step-by-Step Solution
Solution:
  1. Step 1: Understand fork behavior

    When a child process is forked, it may not be ready to receive messages immediately.
  2. Step 2: Identify timing issue

    Sending messages immediately after fork without waiting for 'message' or 'online' event can cause message loss.
  3. Step 3: Verify other options

    'error' and 'exit' event listeners are correctly implemented; 'send' is valid for forked processes.
  4. Final Answer:

    The child process may not be ready to receive messages immediately after fork -> Option D
  5. Quick Check:

    Wait for child readiness before sending messages [OK]
Quick Trick: Wait for 'online' event before sending messages [OK]
Common Mistakes:
  • Assuming child is ready immediately after fork
  • Misusing event listeners like 'error' or 'exit'
  • Believing 'send' is invalid with forked processes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes