Bird
0
0

What will be the output of this Node.js code snippet using a worker thread?

medium📝 component behavior Q4 of 15
Node.js - Worker Threads
What will be the output of this Node.js code snippet using a worker thread?
const { Worker, isMainThread } = require('worker_threads');
if (isMainThread) {
  const worker = new Worker(__filename);
  worker.on('message', msg => console.log(msg));
} else {
  parentPort.postMessage('Hello from worker');
}
AHello from worker
BError: parentPort is not defined
Cundefined
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Check if 'parentPort' is imported

    The code uses 'parentPort.postMessage' but does not import 'parentPort' from 'worker_threads'.
  2. Step 2: Understand the error caused

    Since 'parentPort' is undefined, the code will throw a ReferenceError.
  3. Final Answer:

    Error: parentPort is not defined -> Option B
  4. Quick Check:

    Missing import causes error = C [OK]
Quick Trick: Always import 'parentPort' to communicate from worker [OK]
Common Mistakes:
  • Forgetting to import 'parentPort'
  • Assuming message logs without event listener
  • Confusing isMainThread logic

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes