0
0
NodejsConceptBeginner · 4 min read

When to Use Worker Threads in Node.js: Guide and Examples

Use worker_threads in Node.js when you need to run CPU-intensive tasks without blocking the main event loop. They allow you to run JavaScript code in parallel threads, improving performance for heavy computations or tasks that would otherwise freeze your app.
⚙️

How It Works

Node.js normally runs JavaScript code on a single thread, which means it can only do one thing at a time. This is great for handling many small tasks quickly, but if you have a heavy task like complex calculations, it can block everything else.

Worker threads let you create separate threads that run alongside the main thread. Think of it like having extra helpers in a kitchen: while the main chef keeps cooking simple dishes, helpers work on complicated recipes without slowing down the kitchen.

Each worker thread runs its own JavaScript environment and can communicate with the main thread using messages. This way, your app stays responsive while heavy work happens in the background.

💻

Example

This example shows how to use a worker thread to calculate the sum of numbers without blocking the main thread.

javascript
import { Worker, isMainThread, parentPort } from '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);
  });
  worker.on('exit', (code) => {
    if (code !== 0) console.error(`Worker stopped with exit code ${code}`);
  });
} else {
  // Heavy computation in worker thread
  let sum = 0;
  for (let i = 1; i <= 1e7; i++) {
    sum += i;
  }
  parentPort.postMessage(sum);
}
Output
Sum from worker: 50000005000000
🎯

When to Use

Use worker threads when your Node.js app needs to do heavy CPU work that would block the main thread and slow down handling user requests or other tasks.

  • Complex calculations like image processing, encryption, or data analysis
  • Running multiple tasks in parallel to improve performance
  • Handling CPU-heavy tasks without freezing the user interface or server responses

For simple I/O tasks like reading files or network calls, worker threads are not needed because Node.js handles those efficiently with its event loop.

Key Points

  • Worker threads run JavaScript in parallel to the main thread.
  • They help keep your app responsive during heavy CPU tasks.
  • Communication between threads happens via message passing.
  • Use them only for CPU-intensive work, not for I/O tasks.
  • Worker threads require Node.js 12 or newer.

Key Takeaways

Use worker threads to run CPU-heavy tasks without blocking the main Node.js thread.
They run JavaScript code in parallel threads and communicate via messages.
Ideal for complex calculations, data processing, or parallel task execution.
Avoid using worker threads for I/O-bound tasks since Node.js handles those efficiently.
Worker threads require Node.js version 12 or higher.