Parallel computation
Offload CPU-bound calculations so the event loop remains responsive.
Node.js · Module
Node.js worker_threads runs JavaScript in parallel worker threads, primarily for CPU-intensive tasks. Workers communicate through message ports and can transfer or share memory.
The module provides independent JavaScript execution threads. A parent thread starts a Worker, and the threads communicate through message ports; ArrayBuffer objects can be transferred and SharedArrayBuffer objects can be shared.
new Worker(filename[, options])| Name | Type | Description |
|---|---|---|
filename | string | Path to the worker's main script; it must be absolute or begin with ./ or ../ when relative. |
options | Object | Optional Worker configuration, including execution and resource settings. |
A Worker instance representing the newly started execution thread.
const { Worker, isMainThread, parentPort } = require('node:worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
worker.once('message', (result) => console.log(result));
worker.once('error', console.error);
} else {
parentPort.postMessage(6 * 7);
}Creates a worker from the current file and exchanges one message with it.
Offload CPU-bound calculations so the event loop remains responsive.
Run independent JavaScript tasks concurrently within one Node.js process.
Exchange structured data or buffers between a parent and worker.
Worker threads run JavaScript in parallel in independent execution threads. They are intended mainly for CPU-intensive work, while asynchronous I/O is generally more efficient without workers.
Follow-up: How can worker and parent exchange data? Through message ports using postMessage and message events; ArrayBuffer instances may be transferred and SharedArrayBuffer instances shared.
The Worker class represents an independent JavaScript execution thread. Most Node.js APIs are available inside it, and the parent communicates with it through its message interface.
Follow-up: How does this differ from child_process? Workers can share memory by transferring ArrayBuffer instances or sharing SharedArrayBuffer instances.
The module exposes communication primitives such as parentPort and MessageChannel. A worker uses parentPort to communicate with its spawning thread, while MessageChannel provides an asynchronous two-way channel.
Follow-up: What filename forms are accepted by Worker? The path must be absolute or relative to the current working directory beginning with ./ or ../.
WorkerMessageChannelMessagePortparentPortisMainThreadworkerDataSharedArrayBuffer