Workers
Offload CPU
Node runs JavaScript on a single thread, so a heavy loop blocks every request until it ends. The classic demo is a slow Fibonacci function that freezes the whole server.
Workers move that computation to a separate thread with its own event loop. The main thread stays free to answer requests while the worker crunches numbers. The program runs the loop on the main thread and prints the Fibonacci number it reached.
function fib(n: number): number { if (n < 2) { return n; } return fib(n - 1) + fib(n - 2); } const slow: number = fib(40); console.log(slow);
102334155
Worker sketch
A worker runs a separate script file in a separate thread. The main thread creates it with new Worker and points at the script path.
Communication stays event based: the worker posts its result, and the main thread listens for a message event. Neither side shares variables, they only exchange messages. The block writes a small worker script, starts it and prints the number the worker posts back.
import { Worker } from "node:worker_threads"; import { writeFileSync } from "node:fs"; // fib.js, written here so the block runs alone writeFileSync("fib.js", ` function fib(n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); } require("node:worker_threads").parentPort.postMessage(fib(20)); `); const worker = new Worker("./fib.js"); worker.on("message", function (value): void { console.log(value); });
6765
Post messages
Both sides send data with postMessage and receive it through message listeners. Only clonable values travel across the boundary, which rules out functions and live sockets.
Add an error listener next to the message listener from day one. Worker crashes then surface as events instead of silent hangs. The block starts the same worker, posts a message to it and prints the number that arrives; the error listener stays ready.
import { Worker } from "node:worker_threads"; import { writeFileSync } from "node:fs"; // fib.js, written here so the block runs alone writeFileSync("fib.js", ` function fib(n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); } require("node:worker_threads").parentPort.postMessage(fib(20)); `); const worker = new Worker("./fib.js"); worker.on("message", function (value): void { console.log(value); }); worker.postMessage(40); worker.on("error", function (err): void { console.log(err); });
6765
Share carefully
Workers do not share memory by default, so each side sees its own copy of the data. Treat every message as a snapshot and design the protocol around small explicit payloads.
Shared buffers exist but add real complexity around locking and ordering. Stay with plain messages until profiling proves that copying is the bottleneck. The program asks whether it runs on the main thread and prints its role.
import { isMainThread } from "node:worker_threads"; if (isMainThread) { console.log("main thread plans work"); } else { console.log("worker computes"); }
main thread plans work
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why does a heavy loop freeze a Node server?
Answer
JavaScript runs on one thread, so the loop blocks the event loop
Nothing else runs on the thread until the loop ends, which is why the work moves to a worker.
-
What does a worker have of its own?
Answer
A thread and an event loop
The separate thread runs its own script, so the main thread stays free.
-
How do the main thread and a worker exchange data?
Answer
With messages:
postMessagesends, a message listener receivesOnly clonable values travel across the boundary, so functions and live sockets cannot be sent.
-
Why listen for the error event from day one?
Answer
A worker crash then surfaces as an event instead of a silent hang
Without the listener a failing worker can leave the main thread waiting for a message that never comes.
-
What does this program print?
function fib(n: number): number { if (n < 2) { return n; } return fib(n - 1) + fib(n - 2); } console.log(fib(10));Answer
55
The tenth Fibonacci number in this numbering is 55, computed by the same recursion the lesson uses.
-
What does this program print?
import { isMainThread } from "node:worker_threads"; if (isMainThread) { console.log("main"); } else { console.log("worker"); }Answer
main
The program is started on the main thread, so the flag is true there.
-
What does this program print?
function fib(n: number): number { return n < 2 ? n : fib(n - 1) + fib(n - 2); } console.log(fib(0), fib(1), fib(2), fib(3));Answer
0 1 1 2
The first two values are the base cases, and each later one is the sum of the two before it.
-
What does this program print?
const jobs: number[] = [1, 2, 3]; let done = 0; for (const job of jobs) { done += job; } console.log(done, jobs.length);Answer
6 3
The jobs add up to six, and the array holds three of them.
-
What does this program print?
import { isMainThread, threadId } from "node:worker_threads"; console.log(isMainThread, threadId);Answer
true 0
The program starts on the main thread, which reports itself as the main thread and carries thread id zero.
-
What does the compiler say about this program?
import { Worker } from "node:worker_threads"; const worker = new Worker(40); console.log(worker);Answer
error TS2345: Argument of type 'number' is not assignable to parameter of type 'string | URL'.
The constructor takes the path or URL of the script, not the number to compute.
Article author: Arthur Isaev