Getting Started With Worker Thread in NodeJS

NodeJS v11.7.0 is released and we have one of the most asked feature requests i.e threads. As we all know, Node provides the developer with a single-threaded system and internally uses threads to manage various I/O calls which work great but when we do CPU intensive task then Node doesn’t perform up to mark.

Well no more, with the release of the worker threads, we can use threads and write CPU intensive code in Node.

Here is what the documentation of Node says about the worker threads:

Workers (threads) are useful for performing CPU-intensive JavaScript operations. They will not help much with I/O-intensive work. Node.js’s built-in asynchronous I/O operations are more efficient than Workers can be.

Update your Node version to the latest and let’s get started with the code.

Here is sample code to get started.

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 stopped with exit code ${code}`));

async function run() {
  const result = await runService('abc.js')

run().catch(err => console.error(err))

Here is the worker.js:

const { workerData, parentPort } = require('worker_threads')

// You can do any heavy stuff here, in a synchronous way
// without blocking the "main thread"

console.log('Going to write tons of content on file '+workerData);
parentPort.postMessage({ fileName: workerData, status: 'Done' })

Now run the code using the following command:

$ node workerthread.js

Here is the output:

Node worker thread

In worker, we send the workerData to the child process and get it back using the postMessage function.

Well, that’s it. This is the simplest example to get started.

For more information, visit the official documentation.


Personally, I think this is great to have a feature. Node is always criticized for its bad CPU intensive performance and with the help of web worker we can achieve the results and get the good part of threads without actually creating a deadlock and bottleneck situation in the code.

I will develop a complete and real-world project soon with worker threads so stay tuned.


Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126