Worker Thread
If the CPU needs a lot of memory to process a user request or a logic, then that task can be CPU intensive, that's why we should use Workers (threads) for performing those CPU-intensive taksks. They are lightweight and cheap as compared to other resources (child processes, cluster module).
Code example
mainThread.js
const { Worker, setEnvironmentData, isMainThread } = require('worker_threads')
const runService = (workerData) => {
console.log('I"m the main thread ',isMainThread); // should be true
return new Promise((resolve, reject) => {
const worker = new Worker('./test.js', { workerData });
worker.on('message', resolve);
worker.on('error', reject);
worker.on('exit', (code) => {
if (code !== 0)
reject(new Error(`Worker stopped with exit code ${code}`));
});
worker.postMessage('Start task');
})
}
const run = async () => {
setEnvironmentData('Hello', 'World!');
const result = await runService({ str: 'data from worker ' })
console.log(result);
}
run().catch(err => console.error(err))
worker.js
const { workerData, parentPort, getEnvironmentData, isMainThread } = require('worker_threads');
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
console.log('Is worker the main thread ', isMainThread); // should be false
// You can do any heavy stuff here, in a synchronous way
// without blocking the "main thread"
console.log(workerData);
// clone of data passed to the spawning thread
console.log(getEnvironmentData('Hello'));
parentPort.postMessage({ randomIntFromInterval: workerData.str + randomIntFromInterval(1, 100) });
parentPort.once('message', (message) => {
parentPort.postMessage('Message from main thread ',message);
});