What is Worker Thread in Node.JS?
Worker threads are the useful feature in Node.Js which allows us to run JavaScript code in parallel with the main thread. Before worker threads NodeJ.Js could execute one operation at a time. Worker threads provide the capability to perform parallel processing by creating separate threads.
Worker threads are useful for performing CPU-intensive JavaScript operations, but they don’t not help much with I/O intensive work. They are also able to share memory by transferring ArrayBuffer instances or sharing SharedArrayBuffer instances.
Creating a simple worker-thread
Example: Create two files named worker.js and index.js in your Node.Js project
Javascript
// worker.js const { workerData, parentPort } = require( 'worker_threads' ) console.log( 'Worker Threads by ' + workerData); parentPort.postMessage({ fileName: workerData, status: 'Done' }) |
Javascript
// index.js const { Worker } = require( 'worker_threads' ) function runService(workerData) { return new Promise((resolve, reject) => { const worker = new Worker( './worker.js' , { workerData }); worker.on( 'message' , resolve); worker.on( 'error' , reject); worker.on( 'exit' , (code) => { if (code !== 0) reject( new Error( `Worker Thread stopped with the exit code: ${code}`)); }) }) } async function run() { const result = await runService( 'w3wiki' ) console.log(result); } run(). catch (err => console.error(err)) |
Output: Here, the function runService() return a Promise and runs the worker thread. The function run() is used for calling the function runService() and giving the value for workerData.
Differentiate between worker threads and clusters in Node JS.
In this article, we will learn about worker threads & clusters, along with discussing the significant distinction that differentiates between worker threads & clusters.
Table of Content
- What is Worker Thread in Node.JS?
- What is clusters in Node.JS?
- Difference between Worker threads and Clusters
- Conclusion
Let us first understand what is worker threads and clusters in Node.js?
Contact Us