Skip to main content

worker_threads

Usage in Deno

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:

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.

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

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

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
    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 Jump to heading

            cIv
            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 Jump to heading

            T
            Serializable
            No documentation available
              T
              TransferListItem
              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
                            Back to top