Exports
[<Class>]
type Exports =
static member SHARE_ENV: Symbol
static member isInternalThread: bool
static member isMainThread: bool
static member parentPort: MessagePort option
static member resourceLimits: ResourceLimits
static member threadId: float
static member threadName: string option
static member workerData: obj
static member BroadcastChannel (name: string) : BroadcastChannel
static member MessageChannel () : MessageChannel
static member MessagePort () : MessagePort
static member Worker (filename: U2<string,URL>, ?options: WorkerOptions) : Worker
static member getEnvironmentData (key: Serializable) : Serializable
static member isMarkedAsUntransferable (object: obj) : bool
static member markAsUncloneable (object: obj) : unit
static member markAsUntransferable (object: obj) : unit
static member moveMessagePortToContext (port: MessagePort, contextifiedSandbox: Context) : MessagePort
static member postMessageToThread (threadId: float, value: obj, transferList: Transferable array, ?timeout: float) : Promise<unit>
static member postMessageToThread (threadId: float, value: obj, ?timeout: float) : Promise<unit>
static member receiveMessageOnPort (port: MessagePort) : Result option
static member setEnvironmentData (key: Serializable, ?value: Serializable) : unit| Assembly | Xantham.Fable.Node |
| Attributes | [<Erase>] |
The package's value exports, each bound to its import.
Properties
static member isInternalThread: boolstatic member isMainThread: boolstatic member resourceLimits: ResourceLimitsMethods
static member BroadcastChannel (name: string) : BroadcastChannel
static member BroadcastChannel (name: string) : BroadcastChannelInstances of BroadcastChannel allow asynchronous one-to-many communication with all other BroadcastChannel instances bound to the same channel name.
'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();
}
@since v15.4.0
static member MessageChannel () : MessageChannel
static member MessageChannel () : MessageChannelInstances 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.
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
@since v10.5.0
static member MessagePort () : MessagePort
static member MessagePort () : MessagePortInstances 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 MessagePorts between different Workers.
This implementation matches browser MessagePort s.
@since v10.5.0
static member Worker (filename: U2<string,URL>, ?options: WorkerOptions) : Worker
static member Worker (filename: U2<string,URL>, ?options: WorkerOptions) : WorkerThe 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, andprocess.stderrstreams may be redirected by the parent thread. - The
import { isMainThread } from 'node:worker_threads'variable is set tofalse. - The
import { parentPort } from 'node:worker_threads'message port is available. process.exit()does not stop the whole program, just the single thread, andprocess.abort()is not available.process.chdir()andprocessmethods that set group or user ids are not available.process.envis 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 (unlessworker.SHARE_ENVis passed as theenvoption to theWorkerconstructor). On Windows, unlike the main thread, a copy of the environment variables operates in a case-sensitive manner.process.titlecannot 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_eventsmodule is not supported. - Native add-ons can only be loaded from multiple threads if they fulfill
certain conditions.
Creating Worker instances inside of other Workers is possible.
Like Web Workers 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 theMessagePorts 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.
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();
});
}
@since v10.5.0
static member getEnvironmentData (key: Serializable) : Serializable
static member getEnvironmentData (key: Serializable) : SerializableWithin 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.
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!'.
}
@since v15.12.0, v14.18.0
| Parameter | |
|---|---|
key | Any arbitrary, cloneable JavaScript value that can be used as a key. |
static member isMarkedAsUntransferable (object: obj) : bool
static member isMarkedAsUntransferable (object: obj) : boolCheck if an object is marked as not transferable with markAsUntransferable.
@since v21.0.0
static member markAsUncloneable (object: obj) : unit
static member markAsUncloneable (object: obj) : unitMark an object as not cloneable. If object is used as message in a port.postMessage() call, an error is thrown. This is a no-op if object is a primitive value.
This has no effect on ArrayBuffer, or any Buffer like objects.
This operation cannot be undone.
const { markAsUncloneable } = require('node:worker_threads');
const anyObject = { foo: 'bar' };
markAsUncloneable(anyObject);
const { port1 } = new MessageChannel();
try {
// This will throw an error, because anyObject is not cloneable.
port1.postMessage(anyObject)
} catch (error) {
// error.name === 'DataCloneError'
}
There is no equivalent to this API in browsers.
@since v22.10.0
static member markAsUntransferable (object: obj) : unit
static member markAsUntransferable (object: obj) : unitMark 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 ArrayBuffers it uses for its Buffer pool with this.
This operation cannot be undone.
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.
@since v14.5.0, v12.19.0
static member moveMessagePortToContext (port: MessagePort, contextifiedSandbox: Context) : MessagePort
static member moveMessagePortToContext (port: MessagePort, contextifiedSandbox: Context) : MessagePortTransfer 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() listener are also created in the target context and inherit from its global Object class.
However, the created MessagePort no longer inherits from EventTarget, and only port.onmessage() can be used to receive events using it.
@since v11.13.0
| Parameter | |
|---|---|
port | The message port to transfer. |
contextifiedSandbox | A contextified object as returned by the vm.createContext() method. |
static member postMessageToThread (threadId: float, value: obj, transferList: Transferable array, ?timeout: float) : Promise<unit>
static member postMessageToThread (threadId: float, value: obj, transferList: Transferable array, ?timeout: float) : Promise<unit>Sends a value to another worker, identified by its thread ID.
@since v22.5.0
| Parameter | |
|---|---|
threadId | The target thread ID. If the thread ID is invalid, a ERR_WORKER_MESSAGING_FAILED error will be thrown. If the target thread ID is the current thread ID, a ERR_WORKER_MESSAGING_SAME_THREAD error will be thrown. |
value | The value to send. |
transferList | If one or more MessagePort-like objects are passed in value, a transferList is required for those items or ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST is thrown. See port.postMessage() for more information. |
timeout | Time to wait for the message to be delivered in milliseconds. By default it's undefined, which means wait forever. If the operation times out, a ERR_WORKER_MESSAGING_TIMEOUT error is thrown. |
static member postMessageToThread (threadId: float, value: obj, ?timeout: float) : Promise<unit>
static member postMessageToThread (threadId: float, value: obj, ?timeout: float) : Promise<unit>Sends a value to another worker, identified by its thread ID.
@since v22.5.0
| Parameter | |
|---|---|
threadId | The target thread ID. If the thread ID is invalid, a ERR_WORKER_MESSAGING_FAILED error will be thrown. If the target thread ID is the current thread ID, a ERR_WORKER_MESSAGING_SAME_THREAD error will be thrown. |
value | The value to send. |
transferList | If one or more MessagePort-like objects are passed in value, a transferList is required for those items or ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST is thrown. See port.postMessage() for more information. |
timeout | Time to wait for the message to be delivered in milliseconds. By default it's undefined, which means wait forever. If the operation times out, a ERR_WORKER_MESSAGING_TIMEOUT error is thrown. |
static member receiveMessageOnPort (port: MessagePort) : Result option
static member receiveMessageOnPort (port: MessagePort) : Result optionReceive 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.
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.
@since v12.3.0
static member setEnvironmentData (key: Serializable, ?value: Serializable) : unit
static member setEnvironmentData (key: Serializable, ?value: Serializable) : unitThe worker.setEnvironmentData() API sets the content of worker.getEnvironmentData() in the current thread and all new Worker instances spawned from the current context.
@since v15.12.0, v14.18.0
| Parameter | |
|---|---|
key | Any arbitrary, cloneable JavaScript value that can be used as a key. |
value | Any arbitrary, cloneable JavaScript value that will be cloned and passed automatically to all new Worker instances. If value is passed as undefined, any previously set value for the key will be deleted. |