Bird
0
0

Identify the error in this Node.js worker communication code:

medium📝 Debug Q14 of 15
Node.js - Worker Threads
Identify the error in this Node.js worker communication code:
const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js');
worker.on('message', (data) => {
  console.log('Received:', data);
});
parentPort.postMessage('start');
ACannot call postMessage on the worker instance
BpostMessage should be called on parentPort inside worker, not on worker instance
CMissing error event listener on worker
DThe worker file path is incorrect
Step-by-Step Solution
Solution:
  1. Step 1: Understand where postMessage is called

    In Node.js, postMessage is called on parentPort inside the worker, not on the worker instance in main thread.
  2. Step 2: Identify correct communication method

    The main thread uses worker.postMessage() to send messages to the worker, but inside the worker, parentPort.postMessage() sends messages back.
  3. Final Answer:

    postMessage should be called on parentPort inside worker, not on worker instance -> Option B
  4. Quick Check:

    postMessage usage inside worker = C [OK]
Quick Trick: postMessage on worker sends to worker; inside worker use parentPort.postMessage [OK]
Common Mistakes:
  • Confusing where to call postMessage
  • Ignoring error event listeners
  • Assuming worker file path is wrong without evidence

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes