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.
Check yourself
2 questions. Get them all right to finish this topic.
0 of 2 right so far. Get all two to finish this topic.