Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot find module 'worker_threads' error in production

I created a node js project that utilizes worker threads. The code works fine when I run npm start in VS Code. But when build and copied in Ubuntu server, it show "Cannot find module 'worker_threads'".

Is there additional configuration that must be done when deploying node js with worker threads in production? By the way here how I deploy it in Ubuntu server.

1.) since my project is typecript, I compiled it using 'tsc' command 2.) the 'tsc' command produced 'build' folder 3.) I copied the package.json and package-lock.json into the 'build' folder 4.) zip the 'build' folder and transfer to Ubuntu server using 'scp' command 5.) in Ubuntu server, I unzip the the 'build' folder 6.) I run 'npm install' in the 'build' folder to download dependencies 7.) I the run my program with 'node ./src/main.js' and also 'pm2 start ./src/main/js' to no avail

Other projects without the worker threads deployed without problem using above procedure.

Thanks in advance!

like image 651
Florante Reguis Avatar asked Jun 09 '20 10:06

Florante Reguis


People also ask

What is the use of the Worker_threads module in node JS?

The node:worker_threads module enables the use of threads that execute JavaScript in parallel. To access it: const worker = require('node:worker_threads'); Workers (threads) are useful for performing CPU-intensive JavaScript operations.

What is a worker thread in JavaScript?

Worker threads are responsible for handling CPU-intensive tasks by transferring ArrayBuffer instances. They have proven to be the best solution for CPU performance due to the following features: They run a single process with multiple threads. Executing one event loop per thread.


2 Answers

Maybe your node.js version is below 12.x. Workers are supported after 10.5. Try adding this to your package.json.

"scripts": {
    "start": "node --experimental-worker ./src/main.js"
}
like image 71
Luciano Avatar answered Oct 21 '22 18:10

Luciano


In my Glitch site, I was able to fix this problem by adding this to my package.json:

  "engines": { "node": "16.x" }
like image 30
Joe Avatar answered Oct 21 '22 19:10

Joe