Worker Threads (Node.js)
Worker threads let Node.js run JavaScript in parallel on separate threads, mainly for CPU-intensive work. They prevent heavy computation from blocking the single-threaded event loop and freezing the rest of the app.
Node.js
Node runs your JavaScript on one thread, so a long CPU-bound task (image processing, big calculations, parsing huge data) blocks the event loop and stalls every other request. Worker threads, from the worker_threads module, move that work onto separate threads so the main thread stays responsive.
Each worker runs its own V8 instance and event loop in isolation; you communicate by passing messages (worker.postMessage / parentPort.on('message')) or sharing memory via SharedArrayBuffer. This isolation avoids the shared-state bugs of traditional threading but means you cannot directly share ordinary objects.
Use workers for CPU-bound work, not I/O — Node's async I/O is already non-blocking, so spawning a thread to read a file gains nothing. For scaling across cores to handle more requests, the cluster module or PM2 cluster mode is usually the better tool; reach for worker threads specifically to offload heavy computation.
Syntax
const { Worker } = require("worker_threads");Examples
JavaScript
const { Worker, isMainThread, parentPort } =
require("worker_threads");
if (isMainThread) {
const w = new Worker(__filename);
w.on("message", sum => console.log("sum:", sum));
} else {
let s = 0;
for (let i = 0; i < 1e7; i++) s += i;
parentPort.postMessage(s);
}