0PricingLogin
Node.js Backend Development Bootcamp · Lesson

Spawning Worker Threads and Passing Messages

Create workers, exchange data via postMessage, and use workerData and MessageChannel for structured communication.

Why Worker Threads Exist

Node.js runs your JavaScript on a single thread. That is great for I/O-bound work (HTTP, DB, files) because the event loop never blocks. But a CPU-bound task — image resizing, hashing, parsing huge payloads, crypto — runs synchronously and freezes the entire server until it finishes.

  • I/O-bound → stay on the event loop, use async APIs.
  • CPU-bound → offload to a Worker thread so the main thread keeps serving requests.

The worker_threads module lets you run JavaScript in parallel on separate OS threads, each with its own V8 isolate and event loop.

Spawning Your First Worker

You create a thread with new Worker(filename). The file runs on a fresh thread. Use isMainThread to make one file behave differently depending on where it runs.

Below, the main thread spawns a worker that points back to the same file. The worker branch does the work and exits.

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

if (isMainThread) {
  console.log('main: spawning worker');
  const worker = new Worker(__filename);
  worker.on('exit', (code) => console.log('worker exited with', code));
} else {
  // This branch runs inside the worker thread
  let sum = 0;
  for (let i = 0; i < 1e7; i++) sum += i;
  console.log('worker computed sum =', sum);
}

All lessons in this course

  1. Why the Event Loop Stalls on CPU-Bound Work
  2. Spawning Worker Threads and Passing Messages
  3. Sharing Memory with SharedArrayBuffer and Atomics
  4. Building a Reusable Worker Pool for Throughput
← Back to Node.js Backend Development Bootcamp