Worker threads#

Stability: 2 - Stable

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

import worker_threads from 'node:worker_threads';
'use strict';

const worker_threads = 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 SharedArrayBuffer instances.

import {
  Worker,
  isMainThread,
  parentPort,
  workerData,
} from 'node:worker_threads';

if (!isMainThread) {
  const { parse } = await import('some-js-parsing-library');
  const script = workerData;
  parentPort.postMessage(parse(script));
}

export default function parseJSAsync(script) {
  return new Promise((resolve, reject) => {
    const worker = new Worker(new URL(import.meta.url), {
      workerData: script,
    });
    worker.on('message', resolve);
    worker.once('error', reject);
    worker.once('exit', (code) => {
      if (code !== 0)
        reject(new Error(`Worker stopped with exit code ${code}`));
    });
  });
};
'use strict';

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.once('error', reject);
      worker.once('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.

worker_threads.getEnvironmentData(key)#

  • key <any> Any arbitrary, cloneable JavaScript value that can be used as a <Map> key.
  • Returns: <any>

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(new URL(import.meta.url));
} else {
  console.log(getEnvironmentData('Hello'));  // Prints 'World!'.
}
'use strict';

const {
  Worker,
  isMainThread,
  setEnvironmentData,
  getEnvironmentData,
} = require('node:worker_threads');

if (isMainThread) {
  setEnvironmentData('Hello', 'World!');
  const worker = new Worker(__filename);
} else {
  console.log(getEnvironmentData('Hello'));  // Prints 'World!'.
}

worker_threads.isInternalThread#

Is true if this code is running inside of an internal Worker thread (e.g the loader thread).

// loader.js
import { isInternalThread } from 'node:worker_threads';
console.log(isInternalThread);  // true
// loader.js
'use strict';

const { isInternalThread } = require('node:worker_threads');
console.log(isInternalThread);  // true
// main.js
import { isInternalThread } from 'node:worker_threads';
console.log(isInternalThread);  // false
// main.js
'use strict';

const { isInternalThread } = require('node:worker_threads');
console.log(isInternalThread);  // false

worker_threads.isMainThread#

Is true if this code is not running inside of a Worker thread.

import { Worker, isMainThread } from 'node:worker_threads';

if (isMainThread) {
  // This re-loads the current file inside a Worker instance.
  new Worker(new URL(import.meta.url));
} else {
  console.log('Inside Worker!');
  console.log(isMainThread);  // Prints 'false'.
}
'use strict';

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

if (isMainThread) {
  // This re-loads the current file inside a Worker instance.
  new Worker(__filename);
} else {
  console.log('Inside Worker!');
  console.log(isMainThread);  // Prints 'false'.
}

worker_threads.markAsUntransferable(object)#

  • object <any> Any arbitrary JavaScript value.

Mark an object as not transferable. If object occurs in the transfer list of a port.postMessage() call, an error is thrown. This is a no-op if object is a primitive value.

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. ArrayBuffer.prototype.transfer() is disallowed on such array buffer instances.

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();
try {
  // This will throw an error, because pooledBuffer is not transferable.
  port1.postMessage(typedArray1, [ typedArray1.buffer ]);
} catch (error) {
  // error.name === 'DataCloneError'
}

// The following line prints the contents of typedArray1 -- it still owns
// its memory and has not been transferred. Without
// `markAsUntransferable()`, this would print an empty Uint8Array and the
// postMessage call would have succeeded.
// typedArray2 is intact as well.
console.log(typedArray1);
console.log(typedArray2);
'use strict';

const { MessageChannel, markAsUntransferable } = require('node:worker_threads');

const pooledBuffer = new ArrayBuffer(8);
const typedArray1 = new Uint8Array(pooledBuffer);
const typedArray2 = new Float64Array(pooledBuffer);

markAsUntransferable(pooledBuffer);

const { port1 } = new MessageChannel();
try {
  // This will throw an error, because pooledBuffer is not transferable.
  port1.postMessage(typedArray1, [ typedArray1.buffer ]);
} catch (error) {
  // error.name === 'DataCloneError'
}

// The following line prints the contents of typedArray1 -- it still owns
// its memory and has not been transferred. Without
// `markAsUntransferable()`, this would print an empty Uint8Array and the
// postMessage call would have succeeded.
// typedArray2 is intact as well.
console.log(typedArray1);
console.log(typedArray2);

There is no equivalent to this API in browsers.

worker_threads.isMarkedAsUntransferable(object)#

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

import { markAsUntransferable, isMarkedAsUntransferable } from 'node:worker_threads';

const pooledBuffer = new ArrayBuffer(8);
markAsUntransferable(pooledBuffer);

isMarkedAsUntransferable(pooledBuffer);  // Returns true.
'use strict';

const { markAsUntransferable, isMarkedAsUntransferable } = require('node:worker_threads');

const pooledBuffer = new ArrayBuffer(8);
markAsUntransferable(pooledBuffer);

isMarkedAsUntransferable(pooledBuffer);  // Returns true.

There is no equivalent to this API in browsers.

worker_threads.markAsUncloneable(object)#

  • object <any> Any arbitrary JavaScript value.

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.

import { markAsUncloneable } from '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'
}
'use strict';

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.

worker_threads.moveMessagePortToContext(port, contextifiedSandbox)#

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.

worker_threads.parentPort#

If this thread is a Worker, this is a MessagePort allowing communication with the parent thread. Messages sent using parentPort.postMessage() are available in the parent thread using worker.on('message'), and messages sent from the parent thread using worker.postMessage() are available in this thread using parentPort.on('message').

import { Worker, isMainThread, parentPort } from 'node:worker_threads';

if (isMainThread) {
  const worker = new Worker(new URL(import.meta.url));
  worker.once('message', (message) => {
    console.log(message);  // Prints 'Hello, world!'.
  });
  worker.postMessage('Hello, world!');
} else {
  // When a message from the parent thread is received, send it back:
  parentPort.once('message', (message) => {
    parentPort.postMessage(message);
  });
}
'use strict';

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

if (isMainThread) {
  const worker = new Worker(__filename);
  worker.once('message', (message) => {
    console.log(message);  // Prints 'Hello, world!'.
  });
  worker.postMessage('Hello, world!');
} else {
  // When a message from the parent thread is received, send it back:
  parentPort.once('message', (message) => {
    parentPort.postMessage(message);
  });
}

worker_threads.postMessageToThread(threadId, value[, transferList][, timeout])#

Stability: 1.1 - Active development

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

If the target thread has no listener for the workerMessage event, then the operation will throw a ERR_WORKER_MESSAGING_FAILED error.

If the target thread threw an error while processing the workerMessage event, then the operation will throw a ERR_WORKER_MESSAGING_ERRORED error.

This method should be used when the target thread is not the direct parent or child of the current thread. If the two threads are parent-children, use the require('node:worker_threads').parentPort.postMessage() and the worker.postMessage() to let the threads communicate.

The example below shows the use of of postMessageToThread: it creates 10 nested threads, the last one will try to communicate with the main thread.

import process from 'node:process';
import {
  postMessageToThread,
  threadId,
  workerData,
  Worker,
} from 'node:worker_threads';

const channel = new BroadcastChannel('sync');
const level = workerData?.level ?? 0;

if (level < 10) {
  const worker = new Worker(new URL(import.meta.url), {
    workerData: { level: level + 1 },
  });
}

if (level === 0) {
  process.on('workerMessage', (value, source) => {
    console.log(`${source} -> ${threadId}:`, value);
    postMessageToThread(source, { message: 'pong' });
  });
} else if (level === 10) {
  process.on('workerMessage', (value, source) => {
    console.log(`${source} -> ${threadId}:`, value);
    channel.postMessage('done');
    channel.close();
  });

  await postMessageToThread(0, { message: 'ping' });
}

channel.onmessage = channel.close;
'use strict';

const process = require('node:process');
const {
  postMessageToThread,
  threadId,
  workerData,
  Worker,
} = require('node:worker_threads');

const channel = new BroadcastChannel('sync');
const level = workerData?.level ?? 0;

if (level < 10) {
  const worker = new Worker(__filename, {
    workerData: { level: level + 1 },
  });
}

if (level === 0) {
  process.on('workerMessage', (value, source) => {
    console.log(`${source} -> ${threadId}:`, value);
    postMessageToThread(source, { message: 'pong' });
  });
} else if (level === 10) {
  process.on('workerMessage', (value, source) => {
    console.log(`${source} -> ${threadId}:`, value);
    channel.postMessage('done');
    channel.close();
  });

  postMessageToThread(0, { message: 'ping' });
}

channel.onmessage = channel.close;

worker_threads.receiveMessageOnPort(port)#

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
'use strict';

const { MessageChannel, receiveMessageOnPort } = require('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.

worker_threads.resourceLimits#

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

If this is used in the main thread, its value is an empty object.

worker_threads.SHARE_ENV#

A special value that can be passed as the env option of the Worker constructor, to indicate that the current thread and the Worker thread should share read and write access to the same set of environment variables.

import process from 'node:process';
import { Worker, SHARE_ENV } from 'node:worker_threads';
new Worker('process.env.SET_IN_WORKER = "foo"', { eval: true, env: SHARE_ENV })
  .once('exit', () => {
    console.log(process.env.SET_IN_WORKER);  // Prints 'foo'.
  });
'use strict';

const { Worker, SHARE_ENV } = require('node:worker_threads');
new Worker('process.env.SET_IN_WORKER = "foo"', { eval: true, env: SHARE_ENV })
  .once('exit', () => {
    console.log(process.env.SET_IN_WORKER);  // Prints 'foo'.
  });

worker_threads.setEnvironmentData(key[, value])#

  • key <any> Any arbitrary, cloneable JavaScript value that can be used as a <Map> key.
  • value <any> 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.

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

worker_threads.threadId#

An integer identifier for the current thread. On the corresponding worker object (if there is any), it is available as worker.threadId. This value is unique for each Worker instance inside a single process.

worker_threads.threadName#

A string identifier for the current thread or null if the thread is not running. On the corresponding worker object (if there is any), it is available as worker.threadName.

worker_threads.workerData#

An arbitrary JavaScript value that contains a clone of the data passed to this thread's Worker constructor.

The data is cloned as if using postMessage(), according to the HTML structured clone algorithm.

import { Worker, isMainThread, workerData } from 'node:worker_threads';

if (isMainThread) {
  const worker = new Worker(new URL(import.meta.url), { workerData: 'Hello, world!' });
} else {
  console.log(workerData);  // Prints 'Hello, world!'.
}
'use strict';

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

if (isMainThread) {
  const worker = new Worker(__filename, { workerData: 'Hello, world!' });
} else {
  console.log(workerData);  // Prints 'Hello, world!'.
}

worker_threads.locks#

Stability: 1 - Experimental

An instance of a LockManager that can be used to coordinate access to resources that may be shared across multiple threads within the same process. The API mirrors the semantics of the browser LockManager

Class: Lock#

The Lock interface provides information about a lock that has been granted via locks.request()

lock.name#

The name of the lock.

lock.mode#

The mode of the lock. Either shared or exclusive.

Class: LockManager#

The LockManager interface provides methods for requesting and introspecting locks. To obtain a LockManager instance use

import { locks } from 'node:worker_threads';
'use strict';

const { locks } = require('node:worker_threads');

This implementation matches the browser LockManager API.

locks.request(name[, options], callback)#
  • name <string>
  • options <Object>
    • mode <string> Either 'exclusive' or 'shared'. Default: 'exclusive'.
    • ifAvailable <boolean> If true, the request will only be granted if the lock is not already held. If it cannot be granted, callback will be invoked with null instead of a Lock instance. Default: false.
    • steal <boolean> If true, any existing locks with the same name are released and the request is granted immediately, pre-empting any queued requests. Default: false.
    • signal <AbortSignal> that can be used to abort a pending (but not yet granted) lock request.
  • callback <Function> Invoked once the lock is granted (or immediately with null if ifAvailable is true and the lock is unavailable). The lock is released automatically when the function returns, or—if the function returns a promise—when that promise settles.
  • Returns: <Promise> Resolves once the lock has been released.
import { locks } from 'node:worker_threads';

await locks.request('my_resource', async (lock) => {
  // The lock has been acquired.
});
// The lock has been released here.
'use strict';

const { locks } = require('node:worker_threads');

locks.request('my_resource', async (lock) => {
  // The lock has been acquired.
}).then(() => {
  // The lock has been released here.
});
locks.query()#

Resolves with a LockManagerSnapshot describing the currently held and pending locks for the current process.

import { locks } from 'node:worker_threads';

const snapshot = await locks.query();
for (const lock of snapshot.held) {
  console.log(`held lock: name ${lock.name}, mode ${lock.mode}`);
}
for (const pending of snapshot.pending) {
  console.log(`pending lock: name ${pending.name}, mode ${pending.mode}`);
}
'use strict';

const { locks } = require('node:worker_threads');

locks.query().then((snapshot) => {
  for (const lock of snapshot.held) {
    console.log(`held lock: name ${lock.name}, mode ${lock.mode}`);
  }
  for (const pending of snapshot.pending) {
    console.log(`pending lock: name ${pending.name}, mode ${pending.mode}`);
  }
});

Class: BroadcastChannel extends EventTarget#

Instances of BroadcastChannel allow asynchronous one-to-many communication with all other BroadcastChannel instances bound to the same channel name.

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(new URL(import.meta.url));
} else {
  bc.postMessage('hello from every worker');
  bc.close();
}
'use strict';

const {
  isMainThread,
  BroadcastChannel,
  Worker,
} = require('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();
}

new BroadcastChannel(name)#

  • name <any> The name of the channel to connect to. Any JavaScript value that can be converted to a string using `${name}` is permitted.

broadcastChannel.close()#

Closes the BroadcastChannel connection.

broadcastChannel.onmessage#

  • Type: <Function> Invoked with a single MessageEvent argument when a message is received.

broadcastChannel.onmessageerror#

  • Type: <Function> Invoked with a received message cannot be deserialized.

broadcastChannel.postMessage(message)#

  • message <any> Any cloneable JavaScript value.

broadcastChannel.ref()#

Opposite of unref(). Calling ref() on a previously unref()ed BroadcastChannel 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.

broadcastChannel.unref()#

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

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

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
'use strict';

const { MessageChannel } = require('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

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

This implementation matches browser MessagePorts.

Event: 'close'#

The 'close' event is emitted once either side of the channel has been disconnected.

import { MessageChannel } from 'node:worker_threads';
const { port1, port2 } = new MessageChannel();

// Prints:
//   foobar
//   closed!
port2.on('message', (message) => console.log(message));
port2.once('close', () => console.log('closed!'));

port1.postMessage('foobar');
port1.close();
'use strict';

const { MessageChannel } = require('node:worker_threads');
const { port1, port2 } = new MessageChannel();

// Prints:
//   foobar
//   closed!
port2.on('message', (message) => console.log(message));
port2.once('close', () => console.log('closed!'));

port1.postMessage('foobar');
port1.close();

Event: 'message'#

  • value <any> The transmitted value

The 'message' event is emitted for any incoming message, containing the cloned input of port.postMessage().

Listeners on this event receive a clone of the value parameter as passed to postMessage() and no further arguments.

Event: 'messageerror'#

The 'messageerror' event is emitted when deserializing a message failed.

Currently, this event is emitted when there is an error occurring while instantiating the posted JS object on the receiving end. Such situations are rare, but can happen, for instance, when certain Node.js API objects are received in a vm.Context (where Node.js APIs are currently unavailable).

port.close()#

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.

port.postMessage(value[, transferList])#

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:

import { MessageChannel } from 'node:worker_threads';
const { port1, port2 } = new MessageChannel();