节点:错误的选择:-experimental-worker

时间:2019-09-29 09:44:33

标签: javascript node.js worker-thread

我正在尝试在node.js中使用worker_threads。

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!');
}

我将以上代码保存在index.js中,并在终端上运行node --experimental-worker index.js。 我收到以下错误:

  

节点:错误的选择:--experimental-worker。

我的Mac中安装了v8.16.0个节点。

2 个答案:

答案 0 :(得分:3)

Worker类是在nodejs v10.5.0中添加的。

要使用--experimental-worker,至少需要使用nodejs v10.5.0

有了nodejs v12.x,它很稳定,可以在没有--experimental-worker的情况下使用

下载:nodejs

版本管理器:nvm

答案 1 :(得分:1)

我遇到了同样的问题,但是按照@Estradiaz的建议,我将节点版本从v8.16.0升级到了v.12.13.1,

  1. nvm安装12.13.1
  2. nvm使用12.13.1 然后问题解决了。