Languages
[Edit]
EN

Node.js / JavaScript - run source code in thread

6 points
Created by:
Hayley-Mooney
677

In this short article, we would like to show how we can create new thread in JavaScript and run it under Node.js.

The article shows how to use threads package that bases on worker threads Node.js feature.

Warning: worker threads are supported in Node.js 12+.

 

Simple steps:

1. install threads package using:

 

2. create application files:

Exmaple main.js file:

Exmaple thread.js file:

Note: it is required to use separated files working with worker threads (e.g. thread.js file in the above example).

 

3. run application using the command:

Output:

Hint: to enable ES Modules (import/export keywords) add "type": "module" property to package.json file.

 

Exmaple package.json file content:

 

See also

Edit
  1. Node.js - enable ES Modules (enabling import/export)

References

Edit
  1. https://www.npmjs.com/package/threads
  2. https://nodejs.org/api/worker_threads.html

Alternative titles

  1. Node.js / JavaScript - execute source code in thread
  2. Node.js / JavaScript - create thread
  3. Node.js / JavaScript - run source code in separated thread
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join