4

I am trying to experiment with worker_threads in node.js.

const { Worker, isMainThread, parentPort } = require('worker_threads');
if (isMainThread) {
    // This code is executed in the main thread and not in the worker.

    // Create the worker.
    const worker = new Worker(__filename);
    // Listen for messages from the worker and print them.
    worker.on('message', (msg) => { console.log(msg); });
} else {
    // This code is executed in the worker and not in the main thread.

    // Send a message to the main thread.
    parentPort.postMessage('Hello world!');
}

I save the above code in index.js and run node --experimental-worker index.js on terminal. I get the following error:

node: bad option: --experimental-worker.

I have v8.16.0 of node installed in my mac.

3
  • 1
    can you share documentation? cant find it pre v10.5, added 10.5. nodejs.org/docs/latest-v10.x/api/…
    – Estradiaz
    Sep 29, 2019 at 9:49
  • Hey @Estradiaz, I upgraded the node version and its working now. Thanks! Sep 29, 2019 at 10:15
  • @estradiaz Please turn your comment into an answer
    – Marged
    Sep 29, 2019 at 11:56

2 Answers 2

8

The Worker class was added in nodejs v10.5.0.

To use --experimental-worker one will need at least nodejs v10.5.0

With nodejs v12.x it is stable and can be used without --experimental-worker

Downloads: nodejs

Version Manager: nvm

1

I had same issue, but as suggested by @Estradiaz I upgraded my node version from v8.16.0 to v.12.13.1 by

  1. nvm install 12.13.1
  2. nvm use 12.13.1 then the issue solved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.