Core Modules
Node.js Worker Threads
Worker threads run JavaScript in parallel on separate threads, which is how CPU-heavy work is kept off the main thread. Each worker has its own event loop and memory, and they communicate by message passing.
What is Worker Threads in Node.js?
Worker threads run JavaScript in parallel on separate threads, which is how CPU-heavy work is kept off the main thread. Each worker has its own event loop and memory, and they communicate by message passing.
Why Worker Threads matters
Node’s single thread is fine for I/O but disastrous for computation. A three-second calculation on the main thread freezes every request for three seconds; in a worker it does not.
Worker Threads example
// main.js
import { Worker } from 'node:worker_threads';
function runHeavy(data) {
return new Promise((resolve, reject) => {
const worker = new Worker('./worker.js', { workerData: data });
worker.on('message', resolve);
worker.on('error', reject);
});
}
// worker.js
import { parentPort, workerData } from 'node:worker_threads';
const result = expensiveCalculation(workerData);
parentPort.postMessage(result);Key points to remember
- Use workers for CPU work — never for I/O, which is already asynchronous.
- Starting a worker costs time and memory; pool them for frequent tasks.
- Data is copied between threads unless you use SharedArrayBuffer.
Common mistakes with Worker Threads
- Spawning a worker per request, which is heavier than the work itself.
- Reaching for workers when the real problem is a synchronous file read.
Node.js Worker Threads— Interview Questions & FAQs
When should I use worker threads instead of clustering?+
Worker threads for CPU-bound computation inside one application — image processing, encryption, heavy parsing. Clustering for serving more concurrent requests by running several copies of the whole server.
