Bird
0
0

Identify the error in this worker thread code snippet:

medium📝 Debug Q14 of 15
Node.js - Worker Threads
Identify the error in this worker thread code snippet:
const { Worker } = require('worker_threads');

const worker = new Worker('./worker.js');
worker.on('message', (msg) => console.log(msg));
worker.postMessage('Start');
AWorker file path must be absolute
BMissing import of parentPort in worker.js
CCannot call postMessage on worker instance
DEvent listener 'message' should be 'onmessage'
Step-by-Step Solution
Solution:
  1. Step 1: Check main thread code

    Main thread creates worker and sends message correctly.
  2. Step 2: Common worker.js mistake

    Inside worker.js, parentPort must be imported to receive and send messages.
  3. Final Answer:

    Missing import of parentPort in worker.js -> Option B
  4. Quick Check:

    Worker needs parentPort import to communicate = C [OK]
Quick Trick: Worker.js must import parentPort to handle messages [OK]
Common Mistakes:
  • Thinking postMessage is invalid on worker instance
  • Believing file path must be absolute always
  • Using 'onmessage' instead of 'message' event

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes