When to Use Worker Threads in Node.js: Guide and Examples
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.
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); }
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.