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 should be absolute or URL
BMissing event listener for 'error' event
CCannot create Worker with a string filename
DCannot call postMessage on Worker instance
Step-by-Step Solution
Solution:
  1. Step 1: Check Worker constructor argument

    The Worker constructor expects an absolute path or a URL, not just a relative string like 'worker.js'.
  2. Step 2: Validate other options

    Cannot create Worker with a string filename is incorrect because Worker can be created with a filename if path is correct. Missing event listener for 'error' event is good practice but not an error. Cannot call postMessage on Worker instance is wrong; postMessage is valid on Worker.
  3. Final Answer:

    Worker file path should be absolute or URL -> Option A
  4. Quick Check:

    Worker needs absolute path or URL = C [OK]
Quick Trick: Use absolute path or URL for Worker file [OK]
Common Mistakes:
  • Using relative paths without resolving them
  • Ignoring error event listeners
  • Thinking postMessage is invalid on Worker

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes