2

I'm trying to use "worker_threads" in my react-app for some cpu-intensive works. but react-app can't find "worker_threads" in node.js library.

Here is my code:

const {Worker} = require('worker_threads');
const path = require('path');

function fibonacci_worker(n) {
    return new Promise((resolve,reject) => {
      const w1 = new Worker(path.join(__dirname,'/fib.js'), { workerData: n });
      w1.on('message',e => resolve(e));
      w1.on('error',e => reject(e));
    });
}

"npm start" script throws following error: "Can't resolve 'worker_threads' in 'C:\path\to\fibonacci.js'"

  • node version: 12.13.0
  • react-scripts version: 3.2.0
HesamSe
  • 195
  • 1
  • 2
  • 11

1 Answers1

2

React uses Node.js for runtime tasks such as compilation. You cannot use built-in Node.js tools in the own React app, since the app uses the scope and tools of the browser.

You can find more information about the (unexisting) multithreading of the browser in the following question: Why doesn't JavaScript support multithreading?

Rashomon
  • 5,962
  • 4
  • 29
  • 67
  • Acturally, javascript supports multithreading. This question asked 11 years ago. I used `web-workers` to achieve multithreading in a react-app before. But for some reasons, i want to use `worker_threads`. – HesamSe Oct 26 '19 at 10:14
  • @HesamSeyfollahi I assume the answer is updated because it was edited in 2018. Anyway, the package that you are trying to use is only available in the Node enviroment. React runs in the browser, and doesnt have access to own Node modules. – Rashomon Oct 26 '19 at 10:24
  • What if i wrap worker stuffs in a node package and publish it in npm? Can import a package that uses `worker_threads` in my react app? Here is an example: [link](https://www.npmjs.com/package/hesam-fib) – HesamSe Oct 26 '19 at 12:49
  • 1
    I think it won't work since probably the package use methods of the own API of Node.js since its a very special feature that refers to the core. Anyway you can try just copying the code and pasting it to your project inside the src folder. Theres not need to upload it. – Rashomon Oct 27 '19 at 06:16