Open In App

Node.js Worker Threads

Improve
Improve
Like Article
Like
Save
Share
Report

Worker Threads in Node.js is useful for performing heavy JavaScript tasks. With the help of threads, Worker makes it easy to run javascript codes in parallel making it much faster and efficient. We can do heavy tasks without even disturbing the main thread. Worker threads were not introduced in the older versions of Node. Therefore first update your Node.js for getting started.

Now create two files for implementing the thread as shown below:
Filename: worker.js




const { workerData, parentPort } 
        = require('worker_threads')
  
console.log('Technical Articles on '
                    + workerData);
  
parentPort.postMessage(
    { fileName: workerData, status: 'Done' })


Here, the workerData and parentPort are part of Worker Thread. The workerData is used for fetching the data from the thread and parentPort is used for manipulating the thread. The postMessage() method is used for posting the given message in the console by taking the filename as fetched by workerData.

Filename: 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(
`Stopped the Worker Thread with the exit code: ${code}`));
        })
    })
}
  
async function run() {
    const result = await runService('GeeksForGeeks')
    console.log(result);
}
  
run().catch(err => console.error(err))


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.

Step to run this application: Run the following command:

node index.js

The output for above following command is shown below:

Technical Articles on GeeksForGeeks
{ fileName: 'GeeksForGeeks', status: 'Done' }

Conclusion: With worker threads, we can achieve a much efficient application without creating a deadlock situation. This is how you can import the worker thread in an application and implement the thread.



Last Updated : 08 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads