Index - Node documentation

Usage

import * as mod from "node:worker_threads";

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

const worker = require('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 SharedArrayBufferinstances.

const {
  Worker, isMainThread, parentPort, workerData,
} = require('node:worker_threads');

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 { parse } = require('some-js-parsing-library');
  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.

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

c
Worker

The Worker class represents an independent JavaScript execution thread. Most Node.js APIs are available inside of it.

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
markAsUntransferable

Mark an object as not transferable. If object occurs in the transfer list of a port.postMessage() call, it is ignored.

f
moveMessagePortToContext

Transfer a MessagePort to a different vm Context. The original portobject is rendered unusable, and the returned MessagePort instance takes its place.

f
receiveMessageOnPort

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 theMessagePort's queue.

f
setEnvironmentData

The worker.setEnvironmentData() API sets the content ofworker.getEnvironmentData() in the current thread and all new Workerinstances 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
ResourceLimits
No documentation available
I
WorkerOptions
No documentation available
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