Node.js path · Doing more at once · Topic 8 of 8

Worker threads

Not started

worker_threads runs JavaScript in parallel: each Worker has its own V8 isolate, its own event loop and its own globals. Workers don't share ordinary objects with the main thread; they talk by postMessage, which copies data with the structured clone algorithm, can transfer ArrayBuffers without copying, and can share memory through SharedArrayBuffer and Atomics.

Why it matters: A two-second calculation on the main thread is two seconds in which your server answers nobody.

1

How it works

The explanation, with examples you can run.

Moving work off the main thread

// fib.mjs (run with: node fib.mjs)import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads" const fib = (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2)) if (isMainThread) {  const worker = new Worker(new URL(import.meta.url), { workerData: 40 })  worker.once("message", (result) => console.log("fib(40) =", result))  setInterval(() => console.log("main thread is still free"), 250).unref()} else {  parentPort.postMessage(fib(workerData))}

The same file runs twice: once as the main thread, which starts a worker and keeps ticking, and once inside the worker, which does the slow part and posts the answer back.

When to use one

  • Yes: CPU-heavy JavaScript such as parsing a huge document, image or video processing, or simulations.
  • No: I/O-bound work. Network and file I/O are already asynchronous, and crypto and zlib already use the libuv pool.
  • Reuse them: starting a worker costs time and memory (a whole new isolate), so keep a small pool and send it jobs, one per CPU core at most (os.availableParallelism()).

Separate processes (child_process, or cluster for servers) are the alternative when you want isolation as well as parallelism: a crash in one doesn't take down the others. In browsers, Web Workers follow the same model.

2

Check yourself

2 questions. Get them all right to finish this topic.

  1. 1.Which job gains most from a worker thread?
  2. 2.What happens to an object you send to a worker with postMessage?

0 of 2 right so far. Get all two to finish this topic.