Bird
0
0

This code tries to use workers but has an error:

medium📝 Debug Q14 of 15
Node.js - Worker Threads
This code tries to use workers but has an error:
const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js');
worker.on('message', (msg) => console.log(msg));
worker.postMessage('start');
What is the likely problem here?
AThe worker script must use parentPort to receive messages
BYou cannot send messages to workers using postMessage
CWorker constructor requires a function, not a file path
DMissing cluster module import
Step-by-Step Solution
Solution:
  1. Step 1: Check worker communication setup

    Workers communicate via message passing. The worker script must listen on parentPort to receive messages.
  2. Step 2: Identify missing code in worker.js

    If worker.js does not use parentPort.on('message'), it cannot handle messages sent by postMessage, causing no response or error.
  3. Final Answer:

    The worker script must use parentPort to receive messages -> Option A
  4. Quick Check:

    Worker script needs parentPort listener [OK]
Quick Trick: Worker script must listen on parentPort for messages [OK]
Common Mistakes:
  • Thinking postMessage is invalid for workers
  • Confusing worker_threads with cluster usage
  • Assuming Worker constructor takes a function directly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes