Skip to main content
node__worker_threads.d.ts - Node documentation

Usage in Deno

```typescript import * as mod from "node:node__worker_threads.d.ts"; ```
The `node:worker_threads` module enables the use of threads that execute JavaScript in parallel. To access it: ```js import worker from 'node:worker_threads'; ``` Workers (threads) are useful for performing CPU-intensive JavaScript operations. They do not help much with I/O-intensive work. The Node.js built-in asynchronous I/O operations are more efficient than Workers can be. Unlike `child_process` or `cluster`, `worker_threads` can share memory. They do so by transferring `ArrayBuffer` instances or sharing `SharedArrayBuffer` instances. ```js import { Worker, isMainThread, parentPort, workerData, } from 'node:worker_threads'; import { parse } from 'some-js-parsing-library'; if (isMainThread) { module.exports = function parseJSAsync(script) { return new Promise((resolve, reject) => { const worker = new Worker(__filename, { workerData: script, }); worker.on('message', resolve); worker.on('error', reject); worker.on('exit', (code) => { if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`)); }); }); }; } else { const script = workerData; parentPort.postMessage(parse(script)); } ``` The above example spawns a Worker thread for each `parseJSAsync()` call. In practice, use a pool of Workers for these kinds of tasks. Otherwise, the overhead of creating Workers would likely exceed their benefit. When implementing a worker pool, use the `AsyncResource` API to inform diagnostic tools (e.g. to provide asynchronous stack traces) about the correlation between tasks and their outcomes. See `"Using AsyncResource for a Worker thread pool"` in the `async_hooks` documentation for an example implementation. Worker threads inherit non-process-specific options by default. Refer to `Worker constructor options` to know how to customize worker thread options, specifically `argv` and `execArgv` options.

Classes

c
v
MessageChannel
Instances of the `worker.MessageChannel` class represent an asynchronous, two-way communications channel. The `MessageChannel` has no methods of its own. `new MessageChannel()` yields an object with `port1` and `port2` properties, which refer to linked `MessagePort` instances. ```js import { MessageChannel } from 'node:worker_threads'; const { port1, port2 } = new MessageChannel(); port1.on('message', (message) => console.log('received', message)); port2.postMessage({ foo: 'bar' }); // Prints: received { foo: 'bar' } from the `port1.on('message')` listener ```
c
v
MessagePort
Instances of the `worker.MessagePort` class represent one end of an asynchronous, two-way communications channel. It can be used to transfer structured data, memory regions and other `MessagePort`s between different `Worker`s. This implementation matches [browser `MessagePort`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort) s.
c
Worker
> [!WARNING] Deno compatibility > The `getHeapSnapshot` method is not supported. The `Worker` class represents an independent JavaScript execution thread. Most Node.js APIs are available inside of it. Notable differences inside a Worker environment are: * The `process.stdin`, `process.stdout`, and `process.stderr` streams may be redirected by the parent thread. * The `import { isMainThread } from 'node:worker_threads'` variable is set to `false`. * The `import { parentPort } from 'node:worker_threads'` message port is available. * `process.exit()` does not stop the whole program, just the single thread, and `process.abort()` is not available. * `process.chdir()` and `process` methods that set group or user ids are not available. * `process.env` is a copy of the parent thread's environment variables, unless otherwise specified. Changes to one copy are not visible in other threads, and are not visible to native add-ons (unless `worker.SHARE_ENV` is passed as the `env` option to the `Worker` constructor). On Windows, unlike the main thread, a copy of the environment variables operates in a case-sensitive manner. * `process.title` cannot be modified. * Signals are not delivered through `process.on('...')`. * Execution may stop at any point as a result of `worker.terminate()` being invoked. * IPC channels from parent processes are not accessible. * The `trace_events` module is not supported. * Native add-ons can only be loaded from multiple threads if they fulfill `certain conditions`. Creating `Worker` instances inside of other `Worker`s is possible. Like [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) and the `node:cluster module`, two-way communication can be achieved through inter-thread message passing. Internally, a `Worker` has a built-in pair of `MessagePort` s that are already associated with each other when the `Worker` is created. While the `MessagePort` object on the parent side is not directly exposed, its functionalities are exposed through `worker.postMessage()` and the `worker.on('message')` event on the `Worker` object for the parent thread. To create custom messaging channels (which is encouraged over using the default global channel because it facilitates separation of concerns), users can create a `MessageChannel` object on either thread and pass one of the`MessagePort`s on that `MessageChannel` to the other thread through a pre-existing channel, such as the global one. See `port.postMessage()` for more information on how messages are passed, and what kind of JavaScript values can be successfully transported through the thread barrier. ```js import assert from 'node:assert'; import { Worker, MessageChannel, MessagePort, isMainThread, parentPort, } from 'node:worker_threads'; if (isMainThread) { const worker = new Worker(__filename); const subChannel = new MessageChannel(); worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]); subChannel.port2.on('message', (value) => { console.log('received:', value); }); } else { parentPort.once('message', (value) => { assert(value.hereIsYourPort instanceof MessagePort); value.hereIsYourPort.postMessage('the worker is sending this'); value.hereIsYourPort.close(); }); } ```

Functions

f
getEnvironmentData
Within a worker thread, `worker.getEnvironmentData()` returns a clone of data passed to the spawning thread's `worker.setEnvironmentData()`. Every new `Worker` receives its own copy of the environment data automatically. ```js import { Worker, isMainThread, setEnvironmentData, getEnvironmentData, } from 'node:worker_threads'; if (isMainThread) { setEnvironmentData('Hello', 'World!'); const worker = new Worker(__filename); } else { console.log(getEnvironmentData('Hello')); // Prints 'World!'. } ```
f
markAsUntransferable
> [!WARNING] Deno compatibility > This symbol is not supported. Mark an object as not transferable. If `object` occurs in the transfer list of a `port.postMessage()` call, it is ignored. In particular, this makes sense for objects that can be cloned, rather than transferred, and which are used by other objects on the sending side. For example, Node.js marks the `ArrayBuffer`s it uses for its `Buffer pool` with this. This operation cannot be undone. ```js import { MessageChannel, markAsUntransferable } from 'node:worker_threads'; const pooledBuffer = new ArrayBuffer(8); const typedArray1 = new Uint8Array(pooledBuffer); const typedArray2 = new Float64Array(pooledBuffer); markAsUntransferable(pooledBuffer); const { port1 } = new MessageChannel(); port1.postMessage(typedArray1, [ typedArray1.buffer ]); // The following line prints the contents of typedArray1 -- it still owns // its memory and has been cloned, not transferred. Without // `markAsUntransferable()`, this would print an empty Uint8Array. // typedArray2 is intact as well. console.log(typedArray1); console.log(typedArray2); ``` There is no equivalent to this API in browsers.
f
moveMessagePortToContext
> [!WARNING] Deno compatibility > This symbol is not supported. Transfer a `MessagePort` to a different `vm` Context. The original `port` object is rendered unusable, and the returned `MessagePort` instance takes its place. The returned `MessagePort` is an object in the target context and inherits from its global `Object` class. Objects passed to the [`port.onmessage()`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage) listener are also created in the target context and inherit from its global `Object` class. However, the created `MessagePort` no longer inherits from [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget), and only [`port.onmessage()`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage) can be used to receive events using it.
f
receiveMessageOnPort
> [!WARNING] Deno compatibility > This symbol is not supported. Receive a single message from a given `MessagePort`. If no message is available,`undefined` is returned, otherwise an object with a single `message` property that contains the message payload, corresponding to the oldest message in the `MessagePort`'s queue. ```js import { MessageChannel, receiveMessageOnPort } from 'node:worker_threads'; const { port1, port2 } = new MessageChannel(); port1.postMessage({ hello: 'world' }); console.log(receiveMessageOnPort(port2)); // Prints: { message: { hello: 'world' } } console.log(receiveMessageOnPort(port2)); // Prints: undefined ``` When this function is used, no `'message'` event is emitted and the `onmessage` listener is not invoked.
f
setEnvironmentData
The `worker.setEnvironmentData()` API sets the content of `worker.getEnvironmentData()` in the current thread and all new `Worker` instances spawned from the current context.

Interfaces

c
I
v
BroadcastChannel
Instances of `BroadcastChannel` allow asynchronous one-to-many communication with all other `BroadcastChannel` instances bound to the same channel name. ```js 'use strict'; import { isMainThread, BroadcastChannel, Worker, } from 'node:worker_threads'; const bc = new BroadcastChannel('hello'); if (isMainThread) { let c = 0; bc.onmessage = (event) => { console.log(event.data); if (++c === 10) bc.close(); }; for (let n = 0; n < 10; n++) new Worker(__filename); } else { bc.postMessage('hello from every worker'); bc.close(); } ```
I
WorkerPerformance
No documentation available

Type Aliases

T
Serializable
No documentation available
T
TransferListItem
No documentation available

Variables

v
isMainThread
No documentation available
v
parentPort
No documentation available
v
resourceLimits
No documentation available
v
SHARE_ENV
No documentation available
v
threadId
No documentation available
v
workerData
No documentation available