Worker thread in node js

April 29, 2021 / by Omkar Panaskar in Node js, Technology

A Complete Guide to Worker threads in Node.js


If you are a developer you probably know  is an asynchronous single thread language but in the background it uses multithreading. However, it is quite problematic to do complex CPU intensive operations.

Workers are a way to execute code asynchronously on a separate thread and create a message channel between them. Worker thread introduced in Node v10.x in an experimental flag (–experimental-worker) and stable in Node v12.x.

You can’t load the worker thread module in Node without the experimental-worker flag.

C:\Users\worker thread>  node –experimental-worker -e “require(‘worker_threads’);         console.log(‘success’);”     Success

Worker threads are helpful for complex CPU intensive tasks and not for I/O tasks. 

This module is useful to execute JavaScript in parallel. Unlike cluster and child_process, worker threads efficiently share memory by transferring ArrayBuffer instances and SharedArrayBuffer instances.

Working with single thread  asynchronous Node.js

Node.js runs on a single thread, and there is only each interaction occurring in turn in the event loop. Node.js exclusively javascript which is single-threaded and hence, Node doesn’t have any solution to implement CPU intensive operation. 

Some modules like cluster and child_process help to do this task. However, none of these arrangements was generally embraced because of the execution limit.

Let see the example

SetTimeout method takes time to execute but the “running in loop”  message is displayed immediately. Node.js simply invokes the function but doesn’t block the execution of different bits of code. It will get notified through the callback when the question is done, and we will get the outcome. It will report when the task is completed.


What happens when we are required to do simultaneous extreme stuff? For example, performing complex estimations in memory in a huge dataset. In this situation, the event loop gets blocked and others need to wait until the task is not completed. Let’s consider the following example.

As you see, the function foo() is executed for loop up to 100000000 times. The main thread will be occupied with this task and it will ignore other client requests. To solve this problem we use worker thread.

Working of Worker Thread

Worker thread serves for performing CPU intensive problems. Worker thread provides an approach that builds multiple environments running on independent threads. Worker thread helps solve the problem of blockage of the event loop.

Let’s check the implementation of the worker thread from the following example.
1. index.js

run() function call runWorker() function to execute worker thread. We pass string as workerData through runWorker() function. We define worker constructor inside runWorker(). This constructor works as a thread. We pass two parameters in this worker constructor one is the filename and the other is options. 

  • Filename:  The path of main worker script. The path of this file should be relative or full path.
  • Options:
    • workerData- workerData should be a javascript value that will be cloned and made available as require(‘worker_threads’) this is implement in worker.js file
    • env-Environment variable

Some are event of worker threads

  • message: worker thread invoke parentPort.postMessage() and data will be accessible in message event
  • exit: whenever process.exit() method call worker will stop.
  • error: worker thread throws an uncaught exception and in this situation worker thread terminates its process.
  • online:worker thread has started execution js code

2. Worker.js

This file is boosted by worker thread as we already defined in the worker constructor. worker.js file is parent execution of worker thread. In worker.js file, there are two main parts –  workerData and parentPort. Worker data access the data from the thread and parent port will be a message port enabling communication with the parent thread. To send data from parent to worker, postMessage() method is used. This will send to the message event in the main thread.

Some properties of worker thread

  1. isMainThread: True if it has a master process else false.
  2. WorkerData: Used to fetch data form worker constructor.
  3. parentPort: Its message port instance that turns into the best approach to communicate with parent thread.
  4. ThreadId: Identification of thread and it is given for every thread.

With worker thread, we can accomplish a much more productive application without making a halt circumstance. This is the way you can import the worker thread in an application and carry out the thread. With the proper thread support, we can foresee more engineers and developers from domains like AI, machine learning, and big data begin using Node.js.

Leave a Reply