0
0
NodejsConceptBeginner · 3 min read

Worker Threads in Node.js: What They Are and How They Work

In Node.js, worker threads allow running JavaScript code in parallel on multiple threads, separate from the main event loop. This helps perform CPU-heavy tasks without blocking the main thread, improving app responsiveness.
⚙️

How It Works

Node.js normally runs JavaScript code on a single thread, which handles events and I/O operations. This is like a single cashier serving customers one by one. When a task takes a long time, it blocks the cashier, making others wait.

Worker threads create additional threads that run code independently, like adding more cashiers to serve customers simultaneously. Each worker thread has its own memory and event loop, so heavy tasks don’t block the main thread.

Communication between the main thread and worker threads happens through messages, similar to passing notes between cashiers to coordinate work without interrupting each other.

đź’»

Example

This example shows how to create a worker thread that calculates the sum of numbers without blocking the main thread.

javascript
import { Worker, isMainThread, parentPort } from 'node:worker_threads';

if (isMainThread) {
  const worker = new Worker(new URL(import.meta.url));
  worker.on('message', (result) => {
    console.log('Sum from worker:', result);
  });
  worker.on('error', (err) => {
    console.error('Worker error:', err);
  });
} else {
  // Worker thread code
  let sum = 0;
  for (let i = 1; i <= 100; i++) {
    sum += i;
  }
  parentPort.postMessage(sum);
}
Output
Sum from worker: 5050
🎯

When to Use

Use worker threads when your Node.js app needs to perform CPU-intensive tasks like image processing, data compression, or complex calculations. These tasks can slow down the main thread and make your app unresponsive.

Worker threads let you run these heavy tasks in the background while the main thread continues handling user requests and I/O smoothly. This is especially useful in servers, real-time apps, or any program where responsiveness matters.

âś…

Key Points

  • Worker threads run JavaScript in parallel on separate threads.
  • They help avoid blocking the main event loop with heavy tasks.
  • Communication between threads uses message passing.
  • Each worker has its own memory and event loop.
  • Best for CPU-bound tasks, not for I/O operations.
âś…

Key Takeaways

Worker threads enable parallel JavaScript execution in Node.js to improve performance.
They prevent CPU-heavy tasks from blocking the main event loop.
Use message passing to communicate between main and worker threads.
Ideal for CPU-bound tasks like calculations or data processing.
Each worker thread runs independently with its own memory.