Node.js Worker Threads
JavaScript in Node runs your code on a single main thread. That's perfect for I/O — while one request waits for the database, others are served — but a CPU-heavy calculation (image resizing, hashing a large file, a big loop) blocks everything until it finishes. The node:worker_threads module lets you move such work to separate threads.
Workers vs. the alternatives
| Approach | Runs in | Shares memory? | Best for |
|---|---|---|---|
async I/O (fs, fetch…) |
the main thread + libuv pool | — | waiting on disk/network |
worker_threads |
a new thread, same process | optionally (SharedArrayBuffer) |
CPU-heavy JavaScript |
child_process.fork |
a new process | no | isolation, running other programs |
cluster |
several processes | no | using all cores for an HTTP server |
Each worker has its own event loop, its own global scope and its own copy of modules. Workers communicate with the main thread by message passing.
Your first worker
A worker is created from a file. To keep the example in one file, the script checks isMainThread and runs itself as the worker (__filename):
const { Worker, isMainThread, parentPort, workerData } = require('node:worker_threads');
if (isMainThread) {
const worker = new Worker(__filename, { workerData: { limit: 30 } });
worker.on('message', (msg) => console.log('main received:', msg));
worker.on('error', (err) => console.log('worker failed:', err.message));
worker.on('exit', (code) => console.log('worker exited with code', code));
console.log('main thread keeps running...');
} else {
// This branch runs inside the worker thread
const fib = (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2));
parentPort.postMessage({ n: workerData.limit, fib: fib(workerData.limit) });
}main thread keeps running...
main received: { n: 30, fib: 832040 }
worker exited with code 0
Notice that "main thread keeps running..." prints first: creating the worker doesn't block the main thread.
| Name | Meaning |
|---|---|
isMainThread |
true in the main thread, false inside a worker |
workerData |
a copy of the data passed in the Worker constructor |
parentPort |
inside a worker: the channel back to the main thread |
worker.postMessage(v) |
main → worker message |
parentPort.postMessage(v) |
worker → main message |
Wrapping a worker in a promise
Usually you want to await the result of a worker. A small helper does the job:
const { Worker, isMainThread, parentPort, workerData } = require('node:worker_threads');
function runWorker(data) {
return new Promise((resolve, reject) => {
const worker = new Worker(__filename, { workerData: data });
worker.once('message', resolve);
worker.once('error', reject);
});
}
if (isMainThread) {
(async () => {
// Four sums computed in parallel on four threads
const ranges = [[1, 1e6], [1e6 + 1, 2e6], [2e6 + 1, 3e6], [3e6 + 1, 4e6]];
const parts = await Promise.all(ranges.map(([from, to]) => runWorker({ from, to })));
parts.forEach((p, i) => console.log(`part ${i + 1}: ${p}`));
console.log('total :', parts.reduce((a, b) => a + b, 0));
})();
} else {
let sum = 0;
for (let i = workerData.from; i <= workerData.to; i++) sum += i;
parentPort.postMessage(sum);
}part 1: 500000500000
part 2: 1500000500000
part 3: 2500000500000
part 4: 3500000500000
total : 8000002000000
The workers may finish in any order, but Promise.all keeps the results in the order of the input array, so the output is always the same.
Two-way messages
Messages can flow in both directions. The worker below waits for jobs and replies to each one; sending null tells it to stop:
const { Worker, isMainThread, parentPort } = require('node:worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
const words = ['node', 'worker', 'threads'];
let replies = 0;
worker.on('message', (msg) => {
console.log(msg);
if (++replies === words.length) worker.postMessage(null);
});
worker.on('exit', () => console.log('done'));
for (const w of words) worker.postMessage(w);
} else {
parentPort.on('message', (word) => {
if (word === null) return parentPort.close();
parentPort.postMessage(`${word} -> ${word.toUpperCase()}`);
});
}node -> NODE
worker -> WORKER
threads -> THREADS
done
Messages on one channel arrive in the order they were sent, so the replies come back in order too.
What can be sent?
Messages are copied with the structured clone algorithm: objects, arrays, Map, Set, Date, typed arrays and errors work, but functions and class instances' methods do not. For large binary data you can transfer an ArrayBuffer (zero-copy, the sender loses access) or share memory with a SharedArrayBuffer plus Atomics.
Tip: Starting a worker takes a few milliseconds and some memory. For many small tasks, keep a pool of long-lived workers (libraries like
piscinado this) instead of creating one per task.
Note: Workers don't make I/O faster — Node already does I/O in the background. Use them only for CPU-bound JavaScript.
Test yourself
When should you use worker threads?
- For every database query
- For CPU-heavy JavaScript that would block the event loop
- To read files faster
- To make HTTP requests
How does a worker send a result to the main thread?
- return value
- console.log
- parentPort.postMessage(value)
- process.send(value)
Which of these can NOT be sent with postMessage?
- A Map
- A Date
- A function
- A typed array