Understanding Worker Threads in Node.js

Worker threads are a feature in Node.js that allow you to run JavaScript code in a separate thread from the main Node.js event loop. This can be useful for offloading CPU-intensive tasks to separate threads, which can improve the performance and scalability of your application.

To use worker threads in Node.js, you will need to use the worker_threads module, which is included in Node.js starting from version 12.5.0.

Here’s an example of how you can use worker threads in Node.js:

const { Worker, isMainThread, parentPort } = require('worker_threads');

if (isMainThread) {
  // This code runs in the main thread

  // Create a new worker thread
  const worker = new Worker(__filename);

  // Send a message to the worker thread
  worker.postMessage('Hello, worker!');

  // Listen for messages from the worker thread
  worker.on('message', (message) => {
    console.log(`Received message from worker: ${message}`);
  });
} else {
  // This code runs in the worker thread

  // Listen for messages from the main thread
  parentPort.on('message', (message) => {
    console.log(`Received message from main thread: ${message}`);

    // Send a message back to the main thread
    parentPort.postMessage('Hello, main thread!');
  });
}

In this example, the main thread creates a new worker thread and sends a message to it. The worker thread receives the message and sends a message back to the main thread.

There are several other options and methods available for working with worker threads in Node.js. For more information, you can refer to the documentation for the worker_threads module.

Leave a Reply