Skip to main content

worker_threads

The node:worker_threads module enables the use of threads that execute JavaScript in parallel. To access it:

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.

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.

Usage in Deno

import * as mod from "node:worker_threads";

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.

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 MessagePorts between different Workers.

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.

    f
    isMarkedAsUntransferable

    Check if an object is marked as not transferable with markAsUntransferable.

      f
      markAsUncloneable

      Mark 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.

        f
        markAsUntransferable
        No documentation available
          f
          moveMessagePortToContext
          No documentation available
            f
            receiveMessageOnPort
            No documentation available
              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.

                I
                WorkerPerformance
                No documentation available

                Type Aliases

                T
                Serializable
                No documentation available
                  T
                  TransferListItem
                  No documentation available

                    Variables

                    v
                    isInternalThread
                    No documentation available
                      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

                                  class MessageChannel

                                  Usage in Deno

                                  import { MessageChannel } from "node:worker_threads";
                                  

                                  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.

                                  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
                                  

                                  Properties #

                                  variable MessageChannel

                                  MessageChannel class is a global reference for import { MessageChannel } from 'worker_threads' https://nodejs.org/api/globals.html#messagechannel

                                  Type #

                                  globalThis extends { onmessage: any; MessageChannel: infer T; } ? T : _MessageChannel

                                  class MessagePort

                                  extends EventEmitter

                                  Usage in Deno

                                  import { MessagePort } from "node:worker_threads";
                                  

                                  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 MessagePorts between different Workers.

                                  This implementation matches browser MessagePort s.

                                  Properties #

                                  #addEventListener: EventTarget["addEventListener"]
                                  #dispatchEvent: EventTarget["dispatchEvent"]
                                  #removeEventListener: EventTarget["removeEventListener"]

                                  Methods #

                                  #addListener(
                                  event: "close",
                                  listener: () => void,
                                  ): this
                                  #addListener(
                                  event: "message",
                                  listener: (value: any) => void,
                                  ): this
                                  #addListener(
                                  event: "messageerror",
                                  listener: (error: Error) => void,
                                  ): this
                                  #addListener(
                                  event: string | symbol,
                                  listener: (...args: any[]) => void,
                                  ): this
                                  #close(): void

                                  Disables further sending of messages on either side of the connection. This method can be called when no further communication will happen over this MessagePort.

                                  The 'close' event is emitted on both MessagePort instances that are part of the channel.

                                  #emit(event: "close"): boolean
                                  #emit(
                                  event: "message",
                                  value: any,
                                  ): boolean
                                  #emit(
                                  event: "messageerror",
                                  error: Error,
                                  ): boolean
                                  #emit(
                                  event: string | symbol,
                                  ...args: any[],
                                  ): boolean
                                  #off(
                                  event: "close",
                                  listener: () => void,
                                  ): this
                                  #off(
                                  event: "message",
                                  listener: (value: any) => void,
                                  ): this
                                  #off(
                                  event: "messageerror",
                                  listener: (error: Error) => void,
                                  ): this
                                  #off(
                                  event: string | symbol,
                                  listener: (...args: any[]) => void,
                                  ): this
                                  #on(
                                  event: "close",
                                  listener: () => void,
                                  ): this
                                  #on(
                                  event: "message",
                                  listener: (value: any) => void,
                                  ): this
                                  #on(
                                  event: "messageerror",
                                  listener: (error: Error) => void,
                                  ): this
                                  #on(
                                  event: string | symbol,
                                  listener: (...args: any[]) => void,
                                  ): this
                                  #once(
                                  event: "close",
                                  listener: () => void,
                                  ): this
                                  #once(
                                  event: "message",
                                  listener: (value: any) => void,
                                  ): this
                                  #once(
                                  event: "messageerror",
                                  listener: (error: Error) => void,
                                  ): this
                                  #once(
                                  event: string | symbol,
                                  listener: (...args: any[]) => void,
                                  ): this
                                  #postMessage(
                                  value: any,
                                  transferList?: readonly TransferListItem[],
                                  ): void

                                  Sends a JavaScript value to the receiving side of this channel. value is transferred in a way which is compatible with the HTML structured clone algorithm.

                                  In particular, the significant differences to JSON are:

                                  • value may contain circular references.
                                  • value may contain instances of builtin JS types such as RegExps, BigInts, Maps, Sets, etc.
                                  • value may contain typed arrays, both using ArrayBuffers and SharedArrayBuffers.
                                  • value may contain WebAssembly.Module instances.
                                  • value may not contain native (C++-backed) objects other than:
                                  import { MessageChannel } from 'node:worker_threads';
                                  const { port1, port2 } = new MessageChannel();
                                  
                                  port1.on('message', (message) => console.log(message));
                                  
                                  const circularData = {};
                                  circularData.foo = circularData;
                                  // Prints: { foo: [Circular] }
                                  port2.postMessage(circularData);
                                  

                                  transferList may be a list of ArrayBuffer, MessagePort, and FileHandle objects. After transferring, they are not usable on the sending side of the channel anymore (even if they are not contained in value). Unlike with child processes, transferring handles such as network sockets is currently not supported.

                                  If value contains SharedArrayBuffer instances, those are accessible from either thread. They cannot be listed in transferList.

                                  value may still contain ArrayBuffer instances that are not in transferList; in that case, the underlying memory is copied rather than moved.

                                  import { MessageChannel } from 'node:worker_threads';
                                  const { port1, port2 } = new MessageChannel();
                                  
                                  port1.on('message', (message) => console.log(message));
                                  
                                  const uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);
                                  // This posts a copy of `uint8Array`:
                                  port2.postMessage(uint8Array);
                                  // This does not copy data, but renders `uint8Array` unusable:
                                  port2.postMessage(uint8Array, [ uint8Array.buffer ]);
                                  
                                  // The memory for the `sharedUint8Array` is accessible from both the
                                  // original and the copy received by `.on('message')`:
                                  const sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));
                                  port2.postMessage(sharedUint8Array);
                                  
                                  // This transfers a freshly created message port to the receiver.
                                  // This can be used, for example, to create communication channels between
                                  // multiple `Worker` threads that are children of the same parent thread.
                                  const otherChannel = new MessageChannel();
                                  port2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);
                                  

                                  The message object is cloned immediately, and can be modified after posting without having side effects.

                                  For more information on the serialization and deserialization mechanisms behind this API, see the serialization API of the node:v8 module.

                                  #prependListener(
                                  event: "close",
                                  listener: () => void,
                                  ): this
                                  #prependListener(
                                  event: "message",
                                  listener: (value: any) => void,
                                  ): this
                                  #prependListener(
                                  event: "messageerror",
                                  listener: (error: Error) => void,
                                  ): this
                                  #prependListener(
                                  event: string | symbol,
                                  listener: (...args: any[]) => void,
                                  ): this
                                  #prependOnceListener(
                                  event: "close",
                                  listener: () => void,
                                  ): this
                                  #prependOnceListener(
                                  event: "message",
                                  listener: (value: any) => void,
                                  ): this
                                  #prependOnceListener(
                                  event: "messageerror",
                                  listener: (error: Error) => void,
                                  ): this
                                  #prependOnceListener(
                                  event: string | symbol,
                                  listener: (...args: any[]) => void,
                                  ): this
                                  #ref(): void

                                  Opposite of unref(). Calling ref() on a previously unref()ed port does not let the program exit if it's the only active handle left (the default behavior). If the port is ref()ed, calling ref() again has no effect.

                                  If listeners are attached or removed using .on('message'), the port is ref()ed and unref()ed automatically depending on whether listeners for the event exist.

                                  #removeListener(
                                  event: "close",
                                  listener: () => void,
                                  ): this
                                  #removeListener(
                                  event: "message",
                                  listener: (value: any) => void,
                                  ): this
                                  #removeListener(
                                  event: "messageerror",
                                  listener: (error: Error) => void,
                                  ): this
                                  #removeListener(
                                  event: string | symbol,
                                  listener: (...args: any[]) => void,
                                  ): this
                                  #start(): void

                                  Starts receiving messages on this MessagePort. When using this port as an event emitter, this is called automatically once 'message' listeners are attached.

                                  This method exists for parity with the Web MessagePort API. In Node.js, it is only useful for ignoring messages when no event listener is present. Node.js also diverges in its handling of .onmessage. Setting it automatically calls .start(), but unsetting it lets messages queue up until a new handler is set or the port is discarded.

                                  #unref(): void

                                  Calling unref() on a port allows the thread to exit if this is the only active handle in the event system. If the port is already unref()ed calling unref() again has no effect.

                                  If listeners are attached or removed using .on('message'), the port is ref()ed and unref()ed automatically depending on whether listeners for the event exist.

                                  variable MessagePort

                                  MessagePort class is a global reference for import { MessagePort } from 'worker_threads' https://nodejs.org/api/globals.html#messageport

                                  Type #

                                  globalThis extends { onmessage: any; MessagePort: infer T; } ? T : _MessagePort

                                  class Worker

                                  extends EventEmitter

                                  Usage in Deno

                                  import { Worker } from "node:worker_threads";
                                  

                                  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 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();
                                    });
                                  }
                                  

                                  Constructors #

                                  #Worker(
                                  filename: string | URL,
                                  options?: WorkerOptions,
                                  )
                                  new

                                  Properties #

                                  An object that can be used to query performance information from a worker instance. Similar to perf_hooks.performance.

                                  #resourceLimits: ResourceLimits | undefined
                                  readonly
                                  optional

                                  Provides the set of JS engine resource constraints for this Worker thread. If the resourceLimits option was passed to the Worker constructor, this matches its values.

                                  If the worker has stopped, the return value is an empty object.

                                  #stderr: Readable
                                  readonly

                                  This is a readable stream which contains data written to process.stderr inside the worker thread. If stderr: true was not passed to the Worker constructor, then data is piped to the parent thread's process.stderr stream.

                                  #stdin: Writable | null
                                  readonly

                                  If stdin: true was passed to the Worker constructor, this is a writable stream. The data written to this stream will be made available in the worker thread as process.stdin.

                                  #stdout: Readable
                                  readonly

                                  This is a readable stream which contains data written to process.stdout inside the worker thread. If stdout: true was not passed to the Worker constructor, then data is piped to the parent thread's process.stdout stream.

                                  #threadId: number
                                  readonly

                                  An integer identifier for the referenced thread. Inside the worker thread, it is available as import { threadId } from 'node:worker_threads'. This value is unique for each Worker instance inside a single process.

                                  Methods #

                                  #addListener(
                                  event: "error",
                                  listener: (err: Error) => void,
                                  ): this
                                  #addListener(
                                  event: "exit",
                                  listener: (exitCode: number) => void,
                                  ): this
                                  #addListener(
                                  event: "message",
                                  listener: (value: any) => void,
                                  ): this
                                  #addListener(
                                  event: "messageerror",
                                  listener: (error: Error) => void,
                                  ): this
                                  #addListener(
                                  event: "online",
                                  listener: () => void,
                                  ): this
                                  #addListener(
                                  event: string | symbol,
                                  listener: (...args: any[]) => void,
                                  ): this
                                  #emit(
                                  event: "error",
                                  err: Error,
                                  ): boolean
                                  #emit(
                                  event: "exit",
                                  exitCode: number,
                                  ): boolean
                                  #emit(
                                  event: "message",
                                  value: any,
                                  ): boolean
                                  #emit(
                                  event: "messageerror",
                                  error: Error,
                                  ): boolean
                                  #emit(event: "online"): boolean
                                  #emit(
                                  event: string | symbol,
                                  ...args: any[],
                                  ): boolean

                                  Returns a readable stream for a V8 snapshot of the current state of the Worker. See v8.getHeapSnapshot() for more details.

                                  If the Worker thread is no longer running, which may occur before the 'exit' event is emitted, the returned Promise is rejected immediately with an ERR_WORKER_NOT_RUNNING error.

                                  #off(
                                  event: "error",
                                  listener: (err: Error) => void,
                                  ): this
                                  #off(
                                  event: "exit",
                                  listener: (exitCode: number) => void,
                                  ): this
                                  #off(
                                  event: "message",
                                  listener: (value: any) => void,
                                  ): this
                                  #off(
                                  event: "messageerror",
                                  listener: (error: Error) => void,
                                  ): this
                                  #off(
                                  event: "online",
                                  listener: () => void,
                                  ): this
                                  #off(
                                  event: string | symbol,
                                  listener: (...args: any[]) => void,
                                  ): this
                                  #on(
                                  event: "error",
                                  listener: (err: Error) => void,
                                  ): this
                                  #on(
                                  event: "exit",
                                  listener: (exitCode: number) => void,
                                  ): this
                                  #on(
                                  event: "message",
                                  listener: (value: any) => void,
                                  ): this
                                  #on(
                                  event: "messageerror",
                                  listener: (error: Error) => void,
                                  ): this
                                  #on(
                                  event: "online",
                                  listener: () => void,
                                  ): this
                                  #on(
                                  event: string | symbol,
                                  listener: (...args: any[]) => void,
                                  ): this
                                  #once(
                                  event: "error",
                                  listener: (err: Error) => void,
                                  ): this
                                  #once(
                                  event: "exit",
                                  listener: (exitCode: number) => void,
                                  ): this
                                  #once(
                                  event: "message",
                                  listener: (value: any) => void,
                                  ): this
                                  #once(
                                  event: "messageerror",
                                  listener: (error: Error) => void,
                                  ): this
                                  #once(
                                  event: "online",
                                  listener: () => void,
                                  ): this
                                  #once(
                                  event: string | symbol,
                                  listener: (...args: any[]) => void,
                                  ): this
                                  #postMessage(
                                  value: any,
                                  transferList?: readonly TransferListItem[],
                                  ): void

                                  Send a message to the worker that is received via require('node:worker_threads').parentPort.on('message'). See port.postMessage() for more details.

                                  #postMessageToThread(
                                  threadId: number,
                                  value: any,
                                  timeout?: number,
                                  ): Promise<void>

                                  Sends a value to another worker, identified by its thread ID.

                                  #postMessageToThread(
                                  threadId: number,
                                  value: any,
                                  transferList: readonly TransferListItem[],
                                  timeout?: number,
                                  ): Promise<void>
                                  #prependListener(
                                  event: "error",
                                  listener: (err: Error) => void,
                                  ): this
                                  #prependListener(
                                  event: "exit",
                                  listener: (exitCode: number) => void,
                                  ): this
                                  #prependListener(
                                  event: "message",
                                  listener: (value: any) => void,
                                  ): this
                                  #prependListener(
                                  event: "messageerror",
                                  listener: (error: Error) => void,
                                  ): this
                                  #prependListener(
                                  event: "online",
                                  listener: () => void,
                                  ): this
                                  #prependListener(
                                  event: string | symbol,
                                  listener: (...args: any[]) => void,
                                  ): this
                                  #prependOnceListener(
                                  event: "error",
                                  listener: (err: Error) => void,
                                  ): this
                                  #prependOnceListener(
                                  event: "exit",
                                  listener: (exitCode: number) => void,
                                  ): this
                                  #prependOnceListener(
                                  event: "message",
                                  listener: (value: any) => void,
                                  ): this
                                  #prependOnceListener(
                                  event: "messageerror",
                                  listener: (error: Error) => void,
                                  ): this
                                  #prependOnceListener(
                                  event: "online",
                                  listener: () => void,
                                  ): this
                                  #prependOnceListener(
                                  event: string | symbol,
                                  listener: (...args: any[]) => void,
                                  ): this
                                  #ref(): void

                                  Opposite of unref(), calling ref() on a previously unref()ed worker does not let the program exit if it's the only active handle left (the default behavior). If the worker is ref()ed, calling ref() again has no effect.

                                  #removeListener(
                                  event: "error",
                                  listener: (err: Error) => void,
                                  ): this
                                  #removeListener(
                                  event: "exit",
                                  listener: (exitCode: number) => void,
                                  ): this
                                  #removeListener(
                                  event: "message",
                                  listener: (value: any) => void,
                                  ): this
                                  #removeListener(
                                  event: "messageerror",
                                  listener: (error: Error) => void,
                                  ): this
                                  #removeListener(
                                  event: "online",
                                  listener: () => void,
                                  ): this
                                  #removeListener(
                                  event: string | symbol,
                                  listener: (...args: any[]) => void,
                                  ): this
                                  #terminate(): Promise<number>

                                  Stop all JavaScript execution in the worker thread as soon as possible. Returns a Promise for the exit code that is fulfilled when the 'exit' event is emitted.

                                  #unref(): void

                                  Calling unref() on a worker allows the thread to exit if this is the only active handle in the event system. If the worker is already unref()ed calling unref() again has no effect.


                                  function getEnvironmentData

                                  Usage in Deno

                                  import { getEnvironmentData } from "node:worker_threads";
                                  
                                  #getEnvironmentData(key: Serializable): Serializable

                                  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.

                                  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!'.
                                  }
                                  

                                  Parameters #

                                  Any arbitrary, cloneable JavaScript value that can be used as a {Map} key.

                                  Return Type #


                                  function isMarkedAsUntransferable

                                  Usage in Deno

                                  import { isMarkedAsUntransferable } from "node:worker_threads";
                                  
                                  #isMarkedAsUntransferable(object: object): boolean

                                  Check if an object is marked as not transferable with markAsUntransferable.

                                  Parameters #

                                  #object: object

                                  Return Type #

                                  boolean

                                  function markAsUncloneable

                                  Usage in Deno

                                  import { markAsUncloneable } from "node:worker_threads";
                                  
                                  #markAsUncloneable(object: object): void

                                  Mark 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.

                                  Parameters #

                                  #object: object

                                  Return Type #

                                  void

                                  function markAsUntransferable

                                  Usage in Deno

                                  import { markAsUntransferable } from "node:worker_threads";
                                  
                                  #markAsUntransferable(object: object): void

                                  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 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.

                                  Parameters #

                                  #object: object

                                  Return Type #

                                  void

                                  function moveMessagePortToContext

                                  Usage in Deno

                                  import { moveMessagePortToContext } from "node:worker_threads";
                                  
                                  #moveMessagePortToContext(
                                  contextifiedSandbox: Context,
                                  ): MessagePort

                                  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() 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.

                                  Parameters #

                                  The message port to transfer.

                                  #contextifiedSandbox: Context

                                  A contextified object as returned by the vm.createContext() method.

                                  Return Type #


                                  function receiveMessageOnPort

                                  Usage in Deno

                                  import { receiveMessageOnPort } from "node:worker_threads";
                                  
                                  #receiveMessageOnPort(port: MessagePort): { message: any; } | undefined

                                  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.

                                  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.

                                  Parameters #

                                  Return Type #

                                  { message: any; } | undefined

                                  function setEnvironmentData

                                  Usage in Deno

                                  import { setEnvironmentData } from "node:worker_threads";
                                  
                                  #setEnvironmentData(): void

                                  The worker.setEnvironmentData() API sets the content of worker.getEnvironmentData() in the current thread and all new Worker instances spawned from the current context.

                                  Parameters #

                                  Any arbitrary, cloneable JavaScript value that can be used as a {Map} key.

                                  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.

                                  Return Type #

                                  void

                                  class BroadcastChannel

                                  Usage in Deno

                                  import { BroadcastChannel } from "node:worker_threads";
                                  

                                  Instances 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();
                                  }
                                  

                                  Constructors #

                                  #BroadcastChannel(name: string)
                                  new

                                  Properties #

                                  #name: string
                                  readonly
                                  #onmessage: (message: unknown) => void

                                  Invoked with a single `MessageEvent` argument when a message is received.

                                  #onmessageerror: (message: unknown) => void

                                  Invoked with a received message cannot be deserialized.

                                  Methods #

                                  #close(): void

                                  Closes the BroadcastChannel connection.

                                  #postMessage(message: unknown): void

                                  interface BroadcastChannel

                                  extends [NodeJS.RefCounted]

                                  variable BroadcastChannel

                                  BroadcastChannel class is a global reference for import { BroadcastChannel } from 'worker_threads' https://nodejs.org/api/globals.html#broadcastchannel

                                  Type #

                                  globalThis extends { onmessage: any; BroadcastChannel: infer T; } ? T : _BroadcastChannel

                                  interface ResourceLimits

                                  Usage in Deno

                                  import { type ResourceLimits } from "node:worker_threads";
                                  

                                  Properties #

                                  #maxYoungGenerationSizeMb: number | undefined
                                  optional

                                  The maximum size of a heap space for recently created objects.

                                  #maxOldGenerationSizeMb: number | undefined
                                  optional

                                  The maximum size of the main heap in MB.

                                  #codeRangeSizeMb: number | undefined
                                  optional

                                  The size of a pre-allocated memory range used for generated code.

                                  #stackSizeMb: number | undefined
                                  optional

                                  The default maximum stack size for the thread. Small values may lead to unusable Worker instances.


                                  interface WorkerOptions

                                  Usage in Deno

                                  import { type WorkerOptions } from "node:worker_threads";
                                  

                                  Properties #

                                  #argv: any[] | undefined
                                  optional

                                  List of arguments which would be stringified and appended to process.argv in the worker. This is mostly similar to the workerData but the values will be available on the global process.argv as if they were passed as CLI options to the script.

                                  #env:
                                  Dict<string>
                                  | SHARE_ENV
                                  | undefined
                                  optional
                                  #eval: boolean | undefined
                                  optional
                                  #workerData: any
                                  optional
                                  #stdin: boolean | undefined
                                  optional
                                  #stdout: boolean | undefined
                                  optional
                                  #stderr: boolean | undefined
                                  optional
                                  #execArgv: string[] | undefined
                                  optional
                                  #resourceLimits: ResourceLimits | undefined
                                  optional
                                  #transferList: TransferListItem[] | undefined
                                  optional

                                  Additional data to send in the first worker message.

                                  #trackUnmanagedFds: boolean | undefined
                                  optional
                                  #name: string | undefined
                                  optional

                                  An optional name to be appended to the worker title for debugging/identification purposes, making the final title as [worker ${id}] ${name}.



                                  type alias Serializable

                                  Usage in Deno

                                  import { type Serializable } from "node:worker_threads";
                                  

                                  Definition #

                                  string
                                  | object
                                  | number
                                  | boolean
                                  | bigint


                                  variable isInternalThread

                                  Usage in Deno

                                  import { isInternalThread } from "node:worker_threads";
                                  

                                  Type #

                                  boolean

                                  variable isMainThread

                                  Usage in Deno

                                  import { isMainThread } from "node:worker_threads";
                                  

                                  Type #

                                  boolean



                                  variable SHARE_ENV

                                  Usage in Deno

                                  import { SHARE_ENV } from "node:worker_threads";
                                  

                                  Type #

                                  unique symbol

                                  variable threadId

                                  Usage in Deno

                                  import { threadId } from "node:worker_threads";
                                  

                                  Type #

                                  number

                                  variable workerData

                                  Usage in Deno

                                  import { workerData } from "node:worker_threads";
                                  

                                  Type #

                                  any

                                  Did you find what you needed?

                                  Privacy policy