What is worker.isMainThread in Node?

Overview

In this shot, we will learn about the Node thread property isMainThread, which is provided by the worker_threads library in Node.

The library worker_threads provides us APIs which let the developer run code in different threads that run parallel to each other.

isMainThread is a property in the worker_threads library which returns a Boolean value:

  • true: When code is running in the main thread.
  • false: When the code is running in the child threads.

Code example 1

We will write simple code which finds if the current code is running in the main thread or not using the property isMainThread.

const { Worker, isMainThread } = require('worker_threads');
console.log(isMainThread);

Code explanation

  • In line 1, we will require and import the property isMainThread from the library worker_threads.

  • In line 3, we will console log the property isMainThread, which returns a Boolean value.

Output:

Here, the output will be true because it is the main thread.

Code example 2

const { Worker, isMainThread } = require('worker_threads');
if(isMainThread){
new Worker(__filename);
}
console.log(isMainThread);

Code explanation

  • In line 1, we will require and import the property isMainThread from the library worker_threads.

  • In line 3, we will create a new thread using Worker() and pass the current file. It will re-load the file in the new thread.

  • In line 5, we will console log the property isMainThread, which returns a boolean value.

Output:

In this code example, the output will be false because of the new thread created.

Free Resources