EN
Node.js / JavaScript - run source code in thread
6 points
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:
xxxxxxxxxx
1
npm install threads
2. create application files:
Exmaple main.js
file:
xxxxxxxxxx
1
import { spawn, Thread, Worker } from 'threads';
2
3
const thread = await spawn(new Worker('./thread')); // loads ./thread.js file and creates thread
4
5
const result1 = await thread.addNumbers(1, 2);
6
const result2 = await thread.subtractNumbers(1, 2);
7
8
console.log(`1 + 2 = ${result1}`);
9
console.log(`1 - 2 = ${result2}`);
10
11
await Thread.terminate(thread); // releases resources if thread is longer not needed
Exmaple thread.js
file:
xxxxxxxxxx
1
import { expose } from 'threads/worker';
2
3
const addNumbers = (a, b) => {
4
return a + b;
5
};
6
7
const subtractNumbers = (a, b) => {
8
return a - b;
9
};
10
11
expose({ addNumbers, subtractNumbers }); // expose more logic if needed
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:
xxxxxxxxxx
1
node ./main.js
Output:
xxxxxxxxxx
1
1 + 2 = 3
2
1 - 2 = -1
Hint: to enable ES Modules (
import
/export
keywords) add"type": "module"
property topackage.json
file.
Exmaple package.json
file content:
xxxxxxxxxx
1
{
2
"name": "threads-example",
3
"version": "1.0.0",
4
"description": "",
5
"main": "main.js",
6
"scripts": {
7
"test": "echo \"Error: no test specified\" && exit 1"
8
},
9
"author": "",
10
"license": "ISC",
11
"type": "module",
12
"dependencies": {
13
"threads": "^1.7.0"
14
}
15
}