What are worker threads in Node.js

· Category: Node.js

Short answer

Worker threads allow you to run JavaScript in parallel threads, enabling CPU-intensive tasks without blocking the main event loop.

How it works

By default, Node.js runs in a single thread. The worker_threads module spawns new threads that share memory via SharedArrayBuffer and communicate via message passing. Each worker has its own event loop and V8 isolate.

Example

const { Worker, isMainThread, parentPort } = require('worker_threads');
if (isMainThread) {
  const worker = new Worker(__filename);
  worker.on('message', msg => console.log(msg));
} else {
  parentPort.postMessage('Hello from worker');
}

Why it matters

Heavy computation like image processing, data parsing, or mathematical simulations can freeze the event loop. Worker threads distribute CPU load, keeping the main thread responsive for I/O operations.