Using Worker Threads in Node.js

|
| By Sahil Kumar

Node.js is single-threaded by default, which means it can handle only one task at a time in the main thread. While this works well for many applications, it can cause problems when dealing with heavy CPU-intensive tasks, like image processing, encryption, or large calculations.

To solve this, Node.js provides Worker Threads. They allow you to run JavaScript code in parallel threads, so your main thread doesn’t get blocked.

What Are Worker Threads?

Worker Threads are separate threads that can execute JavaScript independently from the main thread. Each worker has its own memory and event loop. This helps improve performance when doing heavy computation without affecting the responsiveness of your app.

When to Use Worker Threads

You should use Worker Threads when:

  • You have CPU-heavy tasks.
  • You want to avoid blocking the main thread.
  • You need parallel processing to improve performance.

Do not use Worker Threads for I/O tasks like reading files or database operations. Node.js already handles I/O efficiently using its asynchronous event loop.

How to Use Worker Threads

Node.js has a built-in module called worker_threads. Let’s see a simple example.

Example: Calculating Factorial Using Worker Threads

1. Create a file worker.js:

const { parentPort } = require('worker_threads');
// Receive data from main thread
parentPort.on('message', (num) => {
let factorial = 1;
for (let i = 1; i <= num; i++) {
factorial *= i;
}
// Send result back to main thread
parentPort.postMessage(factorial);
});

2. Create the main file index.js:

const { Worker } = require('worker_threads');
function calculateFactorial(number) {
return new Promise((resolve, reject) => {
const worker = new Worker('./worker.js');

worker.postMessage(number);
worker.on('message', (result) => {
resolve(result);
});

worker.on('error', (err) => {
reject(err);
});

worker.on('exit', (code) => {
if (code !== 0)
reject(new Error(`Worker stopped with exit code ${code}`));
});
});
}

// Example usage
calculateFactorial(10)
.then(result => console.log(`Factorial: ${result}`))
.catch(err => console.error(err));

Output:
Factorial: 3628800

Key Points About Worker Threads

  • Each worker runs in a separate thread with its own memory.
  • Communication between the main thread and workers is done using postMessage and on(‘message’).
  • You can use multiple workers to run tasks in parallel.
  • Use worker.terminate() to stop a worker if needed.

When Not to Use Worker Threads

  • For simple tasks, using Worker Threads can add unnecessary complexity.
  • For I/O-heavy operations, Node.js async mechanisms are more efficient.

Summary

Worker Threads are a powerful feature in Node.js to handle CPU-intensive tasks without blocking the main thread. By using them, your Node.js applications can stay fast and responsive even when doing heavy computations.
Start small with simple examples like calculating factorial or Fibonacci numbers, and then you can move to more complex tasks like image processing or data transformation in parallel.

Leave a Reply

Your email address will not be published. Required fields are marked *