Comprehensive Guide to Node.js Worker Threads (node:worker_threads)

The node:worker_threads module enables true multithreading in Node.js by running JavaScript in separate threads. While Node.js is traditionally single‑threaded, worker threads allow CPU‑intensive tasks to run in parallel without blocking the event loop. They support shared memory, zero‑copy transfers, worker pools, resource limits, and advanced synchronization APIs. Worker threads are ideal for heavy computation, data processing, and parallel workloads—while async I/O remains best handled by the main thread.

Worker ThreadsisMainThreadworkerDataparentPortMessageChannelSharedArrayBuffer

~3 min read · Updated Dec 30, 2025

1. Introduction


The node:worker_threads module provides a way to run JavaScript in parallel threads. Each worker runs in its own isolated environment but can communicate efficiently with the main thread. This makes worker threads ideal for CPU-bound tasks such as image processing, compression, cryptography, or scientific computation.


2. Accessing the Module


const {
  Worker,
  isMainThread,
  parentPort,
  workerData,
  threadId
} = require('node:worker_threads');

3. Why Use Worker Threads?


  • Parallel CPU work: Offload heavy computations.
  • Shared memory: Use SharedArrayBuffer for fast data exchange.
  • Lower overhead: More lightweight than child_process or cluster.
  • Zero-copy transfer: Transfer ArrayBuffer ownership without cloning.

4. Basic Example


Offloading a heavy Fibonacci calculation to a worker:

// main.js
const { Worker, isMainThread } = require('node:worker_threads');

if (isMainThread) {
  const worker = new Worker(__filename, { workerData: { num: 40 } });

  worker.on('message', (result) => {
    console.log('Fibonacci result:', result);
  });

  worker.on('exit', (code) => {
    console.log('Worker exited with code', code);
  });
} else {
  const { workerData, parentPort } = require('node:worker_threads');

  function fib(n) {
    return n <= 1 ? n : fib(n - 1) + fib(n - 2);
  }

  parentPort.postMessage(fib(workerData.num));
}

5. Core Concepts


5.1 isMainThread


True in the main thread, false inside a worker.


5.2 workerData


Data passed from parent to worker using structured cloning.


5.3 parentPort


Communication channel from worker to parent.


5.4 threadId


Unique identifier for each worker thread.


6. Message Passing & Transfer Lists


6.1 Zero-Copy Transfer


const buffer = new ArrayBuffer(1024);
parentPort.postMessage(buffer, [buffer]); // buffer is detached

6.2 SharedArrayBuffer


True shared memory between threads:

const shared = new SharedArrayBuffer(4);
const view = new Int32Array(shared);
Atomics.store(view, 0, 42);

7. MessageChannel


Create custom communication channels:

const { MessageChannel } = require('node:worker_threads');
const { port1, port2 } = new MessageChannel();
worker.postMessage({ port: port2 }, [port2]);

8. Advanced Features


8.1 Worker Pools


Reuse workers for repeated tasks to reduce overhead.


8.2 SHARE_ENV


new Worker(__filename, { env: worker_threads.SHARE_ENV });

8.3 Resource Limits


new Worker(__filename, {
  resourceLimits: {
    maxOldGenerationSizeMb: 200,
    stackSizeMb: 4
  }
});

8.4 BroadcastChannel


const bc = new BroadcastChannel('updates');
bc.postMessage('Hello workers!');

8.5 Locks API (Experimental)


await locks.request('critical', async () => {
  // Only one worker enters here at a time
});

8.6 Profiling


await worker.startCpuProfile();
await worker.getHeapSnapshot();

8.7 Termination


await worker.terminate();

9. Best Practices


  • Use workers only for CPU-heavy tasks.
  • Use transfer lists for large buffers.
  • Use SharedArrayBuffer carefully to avoid race conditions.
  • Use worker pools for repeated workloads.
  • Avoid blocking the main thread.

10. When Not to Use Worker Threads


  • Simple asynchronous I/O.
  • Very short tasks (overhead > benefit).
  • Tasks that cannot be parallelized.

Conclusion


The node:worker_threads module brings true parallelism to Node.js. With shared memory, zero-copy transfers, worker pools, and advanced synchronization tools, it is ideal for CPU-bound workloads such as image processing, cryptography, compression, and scientific computing. Worker threads significantly enhance performance while keeping the main event loop responsive.


Written & researched by Dr. Shahin Siami

Related Articles

Comprehensive Guide to the Node.js VM Module (node:vm)

The node:vm module allows you to compile and execute JavaScript code inside isolated V8 contexts — essentially creating lightweight sandboxes within your Node.js application. These contexts have their own global scope and can run code independently from the main environment. However, vm is NOT a security sandbox. It is powerful for dynamic code execution, template engines, REPLs, plugin systems, and controlled module execution, but it must never be used to run untrusted code.

Continue

Comprehensive Guide to the V8 Module in Node.js (node:v8)

The node:v8 module exposes low-level APIs that interact directly with the V8 JavaScript engine embedded in Node.js. . These APIs provide access to heap statistics, heap snapshots, coverage tools, serialization mechanisms, V8 flags, object queries, and promise lifecycle hooks. The module is essential for performance analysis, memory debugging, tooling, and advanced Node.js internals work.

Continue

Comprehensive Guide to the Node.js util Module (node:util)

The node:util module provides a powerful collection of helper functions used throughout Node.js core and extremely useful for application developers. These utilities support debugging, inspection, formatting, type checking, callback/Promise conversions, argument parsing, text encoding, MIME handling, and more. It is one of the most versatile and essential toolkits in the Node.js ecosystem.

Continue

Comprehensive Guide to the URL Module in Node.js

The node:url module provides tools for parsing, constructing, and manipulating URLs. Node.js supports two URL APIs: WHATWG URL API — modern, browser‑compatible, standards‑based. Legacy Node.js URL API — older, Node‑specific, now discouraged. The WHATWG API is the recommended approach for all modern applications. It provides a clean, consistent interface for working with URL components, query parameters, and structured URL patterns.

Continue

راهنمای جامع UDP / Datagram Sockets در Node.js

ماژول node:dgram پیاده‌سازی کامل سوکت‌های UDP را در Node.js فراهم می‌کند. UDP یک پروتکل سبک، بدون اتصال (connectionless) و مناسب برای برنامه‌های بلادرنگ مانند VoIP، بازی‌ها، IoT، سیستم‌های پخش (broadcast) و چندپخشی (multicast) است. این ماژول امکان ساخت سوکت، ارسال و دریافت دیتاگرام، مدیریت TTL، عضویت در گروه‌های multicast، کنترل بافرها، و مدیریت رفتار سطح پایین شبکه را فراهم می‌کند.

Continue

Comprehensive Guide to Trace Events and TTY in Node.js

Node.js provides two powerful low‑level modules for diagnostics and terminal interaction: node:trace_events — a high‑resolution tracing system that captures internal activity from V8, Node.js core, and userland code. It is essential for profiling, performance analysis, and deep debugging. node:tty — a module that exposes TTY (terminal) interfaces, enabling advanced CLI tools, raw input handling, cursor control, color detection, and terminal resizing. This guide explains both modules in a clean, structured, and practical way.

Continue