node:worker_threads
Node.js worker_threads module, resolvable via both ESM import and CommonJS
require. Backed by a real host bridge: each Worker runs on its own host
thread with its own GraalVM context, realm, and event loop. Messages cross
threads by structured clone (guest values never cross realms directly).
javascript
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
if (isMainThread) {
const w = new Worker("./worker.js", { workerData: { n: 41 } });
w.on("message", (m) => console.log("got", m));
} else {
parentPort.postMessage(workerData.n + 1);
}Implemented surface
| Export | Description |
|---|---|
Worker | Constructor accepting eval, workerData, transferList, and env options; instances expose postMessage, terminate, ref / unref, and the online / message / messageerror / error / exit events. |
isMainThread | true on the main thread. |
threadId | Numeric ID of the current thread. |
parentPort | The MessagePort to the parent (in a worker). |
workerData | The value passed via the workerData option. |
SHARE_ENV | Sentinel for sharing the parent environment. |
MessageChannel / MessagePort / BroadcastChannel | Channel primitives. |
getEnvironmentData / setEnvironmentData | Cross-worker environment data. |
receiveMessageOnPort(port) | Synchronously drain a queued message. |
markAsUntransferable / isMarkedAsUntransferable / markAsUncloneable | Present as no-ops. |
resourceLimits | The worker's resource-limits object. |
Not implemented
The following throw ERR_METHOD_NOT_IMPLEMENTED when called:
getHeapSnapshot, postMessageToThread, moveMessagePortToContext, and
worker.getHeapSnapshot() / worker.getHeapStatistics().
See also
- Node.js upstream: