問題

我試圖在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. 我收到以下錯誤:

節點:壞選項: – 實驗工作者。

我在我的mac中安裝了v8.16.0節點.

  最佳答案

在nodejs v10.5.0中添加了 Worker 類.

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

使用 nodejs v12.它是穩定的,可以在沒有--experimental-worker的情況下使用

下載: nodejs

版本管理器: nvm

  相同標籤的其他問題

javascriptnode.jsworker-thread