Worker threads
A Node.js program runs its JavaScript on one thread, and a long calculation holds every other callback until it ends. worker_threads is the answer for that case: a second thread with its own event loop and its own copy of the code, which sends messages to the main thread and receives them back. Nothing is shared by default, so there is no lock and no race to learn.
The lesson starts a worker from a string, reads a result out of it, sends a message into it, handles a worker that throws and reads the exit code of one that ends. Every worker here is a few lines of code in a template literal, because eval keeps one program on one page; a real project starts a worker from a file with the same API.
A worker and a message
new Worker(source, { eval: true }) starts a thread and runs the string as its main program. Inside it, parentPort.postMessage sends a value to the main thread, where the message event receives it. The worker ends by itself when it has nothing left to do, and the exit event reports the code.
The worker adds the numbers from one to a hundred and sends the total, and the main thread prints the total and the exit code. Both promises are made before either event can fire, so no message is missed.
The file message.mjs:
import { Worker } from 'node:worker_threads';
const source = `
const { parentPort } = require("node:worker_threads");
let total = 0;
for (let n = 1; n <= 100; n += 1) {
total += n;
}
parentPort.postMessage(total);
`;
const worker = new Worker(source, { eval: true });
const message = new Promise((resolve) => worker.once('message', resolve));
const ended = new Promise((resolve) => worker.once('exit', resolve));
console.log('the worker computed:', await message);
console.log('the worker exited with:', await ended);
node message.mjs
the worker computed: 5050
the worker exited with: 0
The sum arrived in the main thread and the worker ended with zero. The loop is trivial on purpose: the point is the shape, and the same shape holds a hash, an image conversion or a parse of a large file that would otherwise stop the event loop for a second.
postMessage in both directions
The main thread sends a value with worker.postMessage and the worker listens with parentPort.on('message', ...). The value is copied with the structured clone algorithm, so the worker gets an array of its own and changing it changes nothing in the main thread. A worker with a listener stays alive, which is why this program calls terminate when it has its result.
The program sends three numbers to a worker that doubles each one and prints what it sent, what came back and the code that terminate resolved with.
The file data.mjs:
import { Worker } from 'node:worker_threads';
const source = `
const { parentPort } = require("node:worker_threads");
parentPort.on("message", (values) => {
parentPort.postMessage(values.map((value) => value * 2));
});
`;
const worker = new Worker(source, { eval: true });
const message = new Promise((resolve) => worker.once('message', resolve));
worker.postMessage([1, 2, 3]);
console.log('the parent sent:', JSON.stringify([1, 2, 3]));
console.log('the worker returned:', JSON.stringify(await message));
const code = await worker.terminate();
console.log('the worker was stopped with:', code);
node data.mjs
the parent sent: [1,2,3]
the worker returned: [2,4,6]
the worker was stopped with: 1
The array came back doubled, and the worker stopped with one because a terminated worker does not exit with a success. A worker that answers a stream of requests is used like this, and the missing piece is a protocol of your own: an object with a request id, so the main thread knows which answer belongs to which question.
An error in a worker
A worker that throws reports it through the error event of the main thread, and the event carries the error object itself: name, message and stack. The worker ends after the throw, so the main thread has to decide whether the failure is fatal, and the promise form below turns the event into a rejection that a try can catch.
The worker sends one message and then throws, and the main thread prints both.
The file error.mjs:
import { Worker } from 'node:worker_threads';
const source = `
const { parentPort } = require("node:worker_threads");
parentPort.postMessage("before the failure");
throw new Error("the worker broke");
`;
const worker = new Worker(source, { eval: true });
worker.once('message', (text) => {
console.log('the worker said:', text);
});
try {
await new Promise((resolve, reject) => {
worker.once('error', reject);
});
} catch (error) {
console.log('the error event carried:', error.message);
}
node error.mjs
the worker said: before the failure
the error event carried: the worker broke
The message arrived before the failure, because both events are in the order they happened. An error that nobody listens to ends the main thread as well, which is the same rule the lesson on event emitters gave for the error event of any emitter.
The exit code of a worker
A worker has its own process object and its own exit code, and neither is the exit code of the program. The code is reported by the exit event of the worker and it is what the main thread uses to decide whether the job succeeded. A worker that sets process.exitCode does not end the program with that status.
The worker sends a line and sets its code to four, and the main thread prints the message, the code and the fact that it is still running.
The file exit.mjs:
import { Worker } from 'node:worker_threads';
const source = `
const { parentPort } = require("node:worker_threads");
parentPort.postMessage("the work is done");
process.exitCode = 4;
`;
const worker = new Worker(source, { eval: true });
const [message, code] = await Promise.all([
new Promise((resolve) => worker.once('message', resolve)),
new Promise((resolve) => worker.once('exit', resolve)),
]);
console.log('the worker sent:', message);
console.log('the exit code of the worker:', code);
console.log('the main thread is still here');
node exit.mjs
the worker sent: the work is done
the exit code of the worker: 4
the main thread is still here
The code of four belongs to the worker, and the program itself ended with zero. A pool of workers is usually built on exactly this event: each worker reports a code, and the main thread collects the failures and sets one status for the whole run.
Exercises
- Change the calculation in the first worker and check the total. How long does the worker take for a million numbers?
- Send an object with two fields and return one of them doubled. Which clone rule applies to the object?
- Throw a TypeError in the worker and print error.name as well as the message.
- Start two workers at once and wait for both with Promise.all. Does the program end without terminate?
- What does the main thread see when the worker calls process.exit(2)? Is it an exit event or an error event?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a worker share with its parent by default?
Answer
Nothing; the values it receives are copies
Messages are copied with the structured clone algorithm, which is why no lock is needed.
-
How does a worker send a result to the main thread?
Answer
parentPort.postMessage(value)
The port is the channel between the two threads.
-
What does this program print? ``
import { Worker } from "node:worker_threads"; const source =const { parentPort } = require("node:worker_threads"); parentPort.postMessage(2 + 2);; const worker = new Worker(source, { eval: true }); console.log(await new Promise((resolve) => worker.once("message", resolve)));``Answer
4
The worker runs the code, posts the value and ends by itself.
-
Why does a worker that listens for messages need terminate?
Answer
Its own event loop stays alive while it has a listener
A pending listener is work for the worker, so it would wait forever without terminate.
-
What does this program print? ``
import { Worker } from "node:worker_threads"; const source =const { parentPort } = require("node:worker_threads"); parentPort.postMessage([1, 2, 3].map((value) => value * 2));; const worker = new Worker(source, { eval: true }); const result = await new Promise((resolve) => worker.once("message", resolve)); console.log(JSON.stringify(result));``Answer
[2,4,6]
The worker doubled each value and the copy arrived as a new array.
-
How does the main thread hear about a throw in a worker?
Answer
Through the error event of the worker
The event carries the error object, and an unhandled one ends the main thread too.
-
What does this program print? ``
import { Worker } from "node:worker_threads"; const source =process.exitCode = 4;; const worker = new Worker(source, { eval: true }); console.log(await new Promise((resolve) => worker.once("exit", resolve)));``Answer
4
The exit event reports the code of the worker, which is separate from the program.
-
Which import gives the Worker class?
Answer
node:worker_threads
The module is part of the runtime, like node:fs and node:http.
-
Is the exit code of a worker the exit code of the program?
Answer
No, the program sets its own status
The two processes are separate, and the main thread decides what the run reports.
-
What does the eval option of a Worker do?
Answer
It runs the first argument as the code of the worker instead of a file
The lesson uses it to keep one program on one page; a project passes a file URL instead.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev