{ "type": "module", "source": "doc/api/worker_threads.md", "modules": [ { "textRaw": "Worker threads", "name": "worker_threads", "introduced_in": "v10.5.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/worker_threads.js

\n

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

\n
const worker = require('worker_threads');\n
\n

Workers (threads) are useful for performing CPU-intensive JavaScript operations.\nThey do not help much with I/O-intensive work. The Node.js built-in\nasynchronous I/O operations are more efficient than Workers can be.

\n

Unlike child_process or cluster, worker_threads can share memory. They do\nso by transferring ArrayBuffer instances or sharing SharedArrayBuffer\ninstances.

\n
const {\n  Worker, isMainThread, parentPort, workerData\n} = require('worker_threads');\n\nif (isMainThread) {\n  module.exports = function parseJSAsync(script) {\n    return new Promise((resolve, reject) => {\n      const worker = new Worker(__filename, {\n        workerData: script\n      });\n      worker.on('message', resolve);\n      worker.on('error', reject);\n      worker.on('exit', (code) => {\n        if (code !== 0)\n          reject(new Error(`Worker stopped with exit code ${code}`));\n      });\n    });\n  };\n} else {\n  const { parse } = require('some-js-parsing-library');\n  const script = workerData;\n  parentPort.postMessage(parse(script));\n}\n
\n

The above example spawns a Worker thread for each parse() call. In actual\npractice, use a pool of Workers for these kinds of tasks. Otherwise, the\noverhead of creating Workers would likely exceed their benefit.

\n

When implementing a worker pool, use the AsyncResource API to inform\ndiagnostic tools (e.g. to provide asynchronous stack traces) about the\ncorrelation between tasks and their outcomes. See\n\"Using AsyncResource for a Worker thread pool\"\nin the async_hooks documentation for an example implementation.

\n

Worker threads inherit non-process-specific options by default. Refer to\nWorker constructor options to know how to customize worker thread options,\nspecifically argv and execArgv options.

", "methods": [ { "textRaw": "`worker.getEnvironmentData(key)`", "type": "method", "name": "getEnvironmentData", "meta": { "added": [ "v15.12.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "signatures": [ { "return": { "textRaw": "Returns: {any}", "name": "return", "type": "any" }, "params": [ { "textRaw": "`key` {any} Any arbitrary, cloneable JavaScript value that can be used as a {Map} key.", "name": "key", "type": "any", "desc": "Any arbitrary, cloneable JavaScript value that can be used as a {Map} key." } ] } ], "desc": "

Within a worker thread, worker.getEnvironmentData() returns a clone\nof data passed to the spawning thread's worker.setEnvironmentData().\nEvery new Worker receives its own copy of the environment data\nautomatically.

\n
const {\n  Worker,\n  isMainThread,\n  setEnvironmentData,\n  getEnvironmentData,\n} = require('worker_threads');\n\nif (isMainThread) {\n  setEnvironmentData('Hello', 'World!');\n  const worker = new Worker(__filename);\n} else {\n  console.log(getEnvironmentData('Hello'));  // Prints 'World!'.\n}\n
" }, { "textRaw": "`worker.markAsUntransferable(object)`", "type": "method", "name": "markAsUntransferable", "meta": { "added": [ "v14.5.0", "v12.19.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

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

\n

In particular, this makes sense for objects that can be cloned, rather than\ntransferred, and which are used by other objects on the sending side.\nFor example, Node.js marks the ArrayBuffers it uses for its\nBuffer pool with this.

\n

This operation cannot be undone.

\n
const { MessageChannel, markAsUntransferable } = require('worker_threads');\n\nconst pooledBuffer = new ArrayBuffer(8);\nconst typedArray1 = new Uint8Array(pooledBuffer);\nconst typedArray2 = new Float64Array(pooledBuffer);\n\nmarkAsUntransferable(pooledBuffer);\n\nconst { port1 } = new MessageChannel();\nport1.postMessage(typedArray1, [ typedArray1.buffer ]);\n\n// The following line prints the contents of typedArray1 -- it still owns\n// its memory and has been cloned, not transferred. Without\n// `markAsUntransferable()`, this would print an empty Uint8Array.\n// typedArray2 is intact as well.\nconsole.log(typedArray1);\nconsole.log(typedArray2);\n
\n

There is no equivalent to this API in browsers.

" }, { "textRaw": "`worker.moveMessagePortToContext(port, contextifiedSandbox)`", "type": "method", "name": "moveMessagePortToContext", "meta": { "added": [ "v11.13.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {MessagePort}", "name": "return", "type": "MessagePort" }, "params": [ { "textRaw": "`port` {MessagePort} The message port to transfer.", "name": "port", "type": "MessagePort", "desc": "The message port to transfer." }, { "textRaw": "`contextifiedSandbox` {Object} A [contextified][] object as returned by the `vm.createContext()` method.", "name": "contextifiedSandbox", "type": "Object", "desc": "A [contextified][] object as returned by the `vm.createContext()` method." } ] } ], "desc": "

Transfer a MessagePort to a different vm Context. The original port\nobject is rendered unusable, and the returned MessagePort instance\ntakes its place.

\n

The returned MessagePort is an object in the target context and\ninherits from its global Object class. Objects passed to the\nport.onmessage() listener are also created in the target context\nand inherit from its global Object class.

\n

However, the created MessagePort no longer inherits from\nEventTarget, and only port.onmessage() can be used to receive\nevents using it.

" }, { "textRaw": "`worker.receiveMessageOnPort(port)`", "type": "method", "name": "receiveMessageOnPort", "meta": { "added": [ "v12.3.0" ], "changes": [ { "version": "v15.12.0", "pr-url": "https://github.com/nodejs/node/pull/37535", "description": "The port argument can also refer to a `BroadcastChannel` now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object|undefined}", "name": "return", "type": "Object|undefined" }, "params": [ { "textRaw": "`port` {MessagePort|BroadcastChannel}", "name": "port", "type": "MessagePort|BroadcastChannel" } ] } ], "desc": "

Receive a single message from a given MessagePort. If no message is available,\nundefined is returned, otherwise an object with a single message property\nthat contains the message payload, corresponding to the oldest message in the\nMessagePort’s queue.

\n
const { MessageChannel, receiveMessageOnPort } = require('worker_threads');\nconst { port1, port2 } = new MessageChannel();\nport1.postMessage({ hello: 'world' });\n\nconsole.log(receiveMessageOnPort(port2));\n// Prints: { message: { hello: 'world' } }\nconsole.log(receiveMessageOnPort(port2));\n// Prints: undefined\n
\n

When this function is used, no 'message' event is emitted and the\nonmessage listener is not invoked.

" }, { "textRaw": "`worker.setEnvironmentData(key[, value])`", "type": "method", "name": "setEnvironmentData", "meta": { "added": [ "v15.12.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "signatures": [ { "params": [ { "textRaw": "`key` {any} Any arbitrary, cloneable JavaScript value that can be used as a {Map} key.", "name": "key", "type": "any", "desc": "Any arbitrary, cloneable JavaScript value that can be used as a {Map} key." }, { "textRaw": "`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.", "name": "value", "type": "any", "desc": "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." } ] } ], "desc": "

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

" } ], "properties": [ { "textRaw": "`isMainThread` {boolean}", "type": "boolean", "name": "isMainThread", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "desc": "

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

\n
const { Worker, isMainThread } = require('worker_threads');\n\nif (isMainThread) {\n  // This re-loads the current file inside a Worker instance.\n  new Worker(__filename);\n} else {\n  console.log('Inside Worker!');\n  console.log(isMainThread);  // Prints 'false'.\n}\n
" }, { "textRaw": "`parentPort` {null|MessagePort}", "type": "null|MessagePort", "name": "parentPort", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "desc": "

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

\n
const { Worker, isMainThread, parentPort } = require('worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  worker.once('message', (message) => {\n    console.log(message);  // Prints 'Hello, world!'.\n  });\n  worker.postMessage('Hello, world!');\n} else {\n  // When a message from the parent thread is received, send it back:\n  parentPort.once('message', (message) => {\n    parentPort.postMessage(message);\n  });\n}\n
" }, { "textRaw": "`resourceLimits` {Object}", "type": "Object", "name": "resourceLimits", "meta": { "added": [ "v13.2.0", "v12.16.0" ], "changes": [] }, "options": [ { "textRaw": "`maxYoungGenerationSizeMb` {number}", "name": "maxYoungGenerationSizeMb", "type": "number" }, { "textRaw": "`maxOldGenerationSizeMb` {number}", "name": "maxOldGenerationSizeMb", "type": "number" }, { "textRaw": "`codeRangeSizeMb` {number}", "name": "codeRangeSizeMb", "type": "number" }, { "textRaw": "`stackSizeMb` {number}", "name": "stackSizeMb", "type": "number" } ], "desc": "

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

\n

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

" }, { "textRaw": "`SHARE_ENV` {symbol}", "type": "symbol", "name": "SHARE_ENV", "meta": { "added": [ "v11.14.0" ], "changes": [] }, "desc": "

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

\n
const { Worker, SHARE_ENV } = require('worker_threads');\nnew Worker('process.env.SET_IN_WORKER = \"foo\"', { eval: true, env: SHARE_ENV })\n  .on('exit', () => {\n    console.log(process.env.SET_IN_WORKER);  // Prints 'foo'.\n  });\n
" }, { "textRaw": "`threadId` {integer}", "type": "integer", "name": "threadId", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "desc": "

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

" }, { "textRaw": "`worker.workerData`", "name": "workerData", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "desc": "

An arbitrary JavaScript value that contains a clone of the data passed\nto this thread’s Worker constructor.

\n

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

\n
const { Worker, isMainThread, workerData } = require('worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename, { workerData: 'Hello, world!' });\n} else {\n  console.log(workerData);  // Prints 'Hello, world!'.\n}\n
" } ], "classes": [ { "textRaw": "Class: `BroadcastChannel extends EventTarget`", "type": "class", "name": "BroadcastChannel", "meta": { "added": [ "v15.4.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

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

\n
'use strict';\n\nconst {\n  isMainThread,\n  BroadcastChannel,\n  Worker\n} = require('worker_threads');\n\nconst bc = new BroadcastChannel('hello');\n\nif (isMainThread) {\n  let c = 0;\n  bc.onmessage = (event) => {\n    console.log(event.data);\n    if (++c === 10) bc.close();\n  };\n  for (let n = 0; n < 10; n++)\n    new Worker(__filename);\n} else {\n  bc.postMessage('hello from every worker');\n  bc.close();\n}\n
", "methods": [ { "textRaw": "`broadcastChannel.close()`", "type": "method", "name": "close", "meta": { "added": [ "v15.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Closes the BroadcastChannel connection.

" }, { "textRaw": "`broadcastChannel.postMessage(message)`", "type": "method", "name": "postMessage", "meta": { "added": [ "v15.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`message` {any} Any cloneable JavaScript value.", "name": "message", "type": "any", "desc": "Any cloneable JavaScript value." } ] } ] }, { "textRaw": "`broadcastChannel.ref()`", "type": "method", "name": "ref", "meta": { "added": [ "v15.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

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

" }, { "textRaw": "`broadcastChannel.unref()`", "type": "method", "name": "unref", "meta": { "added": [ "v15.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

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

" } ], "properties": [ { "textRaw": "`onmessage` Type: {Function} Invoked with a single `MessageEvent` argument when a message is received.", "type": "Function", "name": "Type", "meta": { "added": [ "v15.4.0" ], "changes": [] }, "desc": "Invoked with a single `MessageEvent` argument when a message is received." }, { "textRaw": "`onmessageerror` Type: {Function} Invoked with a received message cannot be deserialized.", "type": "Function", "name": "Type", "meta": { "added": [ "v15.4.0" ], "changes": [] }, "desc": "Invoked with a received message cannot be deserialized." } ], "signatures": [ { "params": [ { "textRaw": "`name` {any} The name of the channel to connect to. Any JavaScript value that can be converted to a string using ``${name}`` is permitted.", "name": "name", "type": "any", "desc": "The name of the channel to connect to. Any JavaScript value that can be converted to a string using ``${name}`` is permitted." } ] } ] }, { "textRaw": "Class: `MessageChannel`", "type": "class", "name": "MessageChannel", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "desc": "

Instances of the worker.MessageChannel class represent an asynchronous,\ntwo-way communications channel.\nThe MessageChannel has no methods of its own. new MessageChannel()\nyields an object with port1 and port2 properties, which refer to linked\nMessagePort instances.

\n
const { MessageChannel } = require('worker_threads');\n\nconst { port1, port2 } = new MessageChannel();\nport1.on('message', (message) => console.log('received', message));\nport2.postMessage({ foo: 'bar' });\n// Prints: received { foo: 'bar' } from the `port1.on('message')` listener\n
" }, { "textRaw": "Class: `MessagePort`", "type": "class", "name": "MessagePort", "meta": { "added": [ "v10.5.0" ], "changes": [ { "version": [ "v14.7.0" ], "pr-url": "https://github.com/nodejs/node/pull/34057", "description": "This class now inherits from `EventTarget` rather than from `EventEmitter`." } ] }, "desc": "\n

Instances of the worker.MessagePort class represent one end of an\nasynchronous, two-way communications channel. It can be used to transfer\nstructured data, memory regions and other MessagePorts between different\nWorkers.

\n

This implementation matches browser MessagePorts.

", "events": [ { "textRaw": "Event: `'close'`", "type": "event", "name": "close", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "params": [], "desc": "

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

\n
const { MessageChannel } = require('worker_threads');\nconst { port1, port2 } = new MessageChannel();\n\n// Prints:\n//   foobar\n//   closed!\nport2.on('message', (message) => console.log(message));\nport2.on('close', () => console.log('closed!'));\n\nport1.postMessage('foobar');\nport1.close();\n
" }, { "textRaw": "Event: `'message'`", "type": "event", "name": "message", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "params": [ { "textRaw": "`value` {any} The transmitted value", "name": "value", "type": "any", "desc": "The transmitted value" } ], "desc": "

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

\n

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

" }, { "textRaw": "Event: `'messageerror'`", "type": "event", "name": "messageerror", "meta": { "added": [ "v14.5.0", "v12.19.0" ], "changes": [] }, "params": [ { "textRaw": "`error` {Error} An Error object", "name": "error", "type": "Error", "desc": "An Error object" } ], "desc": "

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

\n

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

" } ], "methods": [ { "textRaw": "`port.close()`", "type": "method", "name": "close", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

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

\n

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

" }, { "textRaw": "`port.postMessage(value[, transferList])`", "type": "method", "name": "postMessage", "meta": { "added": [ "v10.5.0" ], "changes": [ { "version": "v15.14.0", "pr-url": "https://github.com/nodejs/node/pull/37917", "description": "Add 'BlockList' to the list of cloneable types." }, { "version": "v15.9.0", "pr-url": "https://github.com/nodejs/node/pull/37155", "description": "Add 'Histogram' types to the list of cloneable types." }, { "version": "v15.6.0", "pr-url": "https://github.com/nodejs/node/pull/36804", "description": "Added `X509Certificate` to the list of cloneable types." }, { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "Added `CryptoKey` to the list of cloneable types." }, { "version": [ "v14.5.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/33360", "description": "Added `KeyObject` to the list of cloneable types." }, { "version": [ "v14.5.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/33772", "description": "Added `FileHandle` to the list of transferable types." } ] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" }, { "textRaw": "`transferList` {Object[]}", "name": "transferList", "type": "Object[]" } ] } ], "desc": "

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

\n

In particular, the significant differences to JSON are:

\n\n
const { MessageChannel } = require('worker_threads');\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (message) => console.log(message));\n\nconst circularData = {};\ncircularData.foo = circularData;\n// Prints: { foo: [Circular] }\nport2.postMessage(circularData);\n
\n

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

\n

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

\n

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

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

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

\n

For more information on the serialization and deserialization mechanisms\nbehind this API, see the serialization API of the v8 module.

", "modules": [ { "textRaw": "Considerations when transferring TypedArrays and Buffers", "name": "considerations_when_transferring_typedarrays_and_buffers", "desc": "

All TypedArray and Buffer instances are views over an underlying\nArrayBuffer. That is, it is the ArrayBuffer that actually stores\nthe raw data while the TypedArray and Buffer objects provide a\nway of viewing and manipulating the data. It is possible and common\nfor multiple views to be created over the same ArrayBuffer instance.\nGreat care must be taken when using a transfer list to transfer an\nArrayBuffer as doing so causes all TypedArray and Buffer\ninstances that share that same ArrayBuffer to become unusable.

\n
const ab = new ArrayBuffer(10);\n\nconst u1 = new Uint8Array(ab);\nconst u2 = new Uint16Array(ab);\n\nconsole.log(u2.length);  // prints 5\n\nport.postMessage(u1, [u1.buffer]);\n\nconsole.log(u2.length);  // prints 0\n
\n

For Buffer instances, specifically, whether the underlying\nArrayBuffer can be transferred or cloned depends entirely on how\ninstances were created, which often cannot be reliably determined.

\n

An ArrayBuffer can be marked with markAsUntransferable() to indicate\nthat it should always be cloned and never transferred.

\n

Depending on how a Buffer instance was created, it may or may\nnot own its underlying ArrayBuffer. An ArrayBuffer must not\nbe transferred unless it is known that the Buffer instance\nowns it. In particular, for Buffers created from the internal\nBuffer pool (using, for instance Buffer.from() or Buffer.allocUnsafe()),\ntransferring them is not possible and they are always cloned,\nwhich sends a copy of the entire Buffer pool.\nThis behavior may come with unintended higher memory\nusage and possible security concerns.

\n

See Buffer.allocUnsafe() for more details on Buffer pooling.

\n

The ArrayBuffers for Buffer instances created using\nBuffer.alloc() or Buffer.allocUnsafeSlow() can always be\ntransferred but doing so renders all other existing views of\nthose ArrayBuffers unusable.

", "type": "module", "displayName": "Considerations when transferring TypedArrays and Buffers" }, { "textRaw": "Considerations when cloning objects with prototypes, classes, and accessors", "name": "considerations_when_cloning_objects_with_prototypes,_classes,_and_accessors", "desc": "

Because object cloning uses the HTML structured clone algorithm,\nnon-enumerable properties, property accessors, and object prototypes are\nnot preserved. In particular, Buffer objects will be read as\nplain Uint8Arrays on the receiving side, and instances of JavaScript\nclasses will be cloned as plain JavaScript objects.

\n
const b = Symbol('b');\n\nclass Foo {\n  #a = 1;\n  constructor() {\n    this[b] = 2;\n    this.c = 3;\n  }\n\n  get d() { return 4; }\n}\n\nconst { port1, port2 } = new MessageChannel();\n\nport1.onmessage = ({ data }) => console.log(data);\n\nport2.postMessage(new Foo());\n\n// Prints: { c: 3 }\n
\n

This limitation extends to many built-in objects, such as the global URL\nobject:

\n
const { port1, port2 } = new MessageChannel();\n\nport1.onmessage = ({ data }) => console.log(data);\n\nport2.postMessage(new URL('https://example.org'));\n\n// Prints: { }\n
", "type": "module", "displayName": "Considerations when cloning objects with prototypes, classes, and accessors" } ] }, { "textRaw": "`port.ref()`", "type": "method", "name": "ref", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

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

\n

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

" }, { "textRaw": "`port.start()`", "type": "method", "name": "start", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

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

\n

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

" }, { "textRaw": "`port.unref()`", "type": "method", "name": "unref", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

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

\n

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

" } ] }, { "textRaw": "Class: `Worker`", "type": "class", "name": "Worker", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "desc": "\n

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

\n

Notable differences inside a Worker environment are:

\n\n

Creating Worker instances inside of other Workers is possible.

\n

Like Web Workers and the cluster module, two-way communication can be\nachieved through inter-thread message passing. Internally, a Worker has a\nbuilt-in pair of MessagePorts that are already associated with each other\nwhen the Worker is created. While the MessagePort object on the parent side\nis not directly exposed, its functionalities are exposed through\nworker.postMessage() and the worker.on('message') event\non the Worker object for the parent thread.

\n

To create custom messaging channels (which is encouraged over using the default\nglobal channel because it facilitates separation of concerns), users can create\na MessageChannel object on either thread and pass one of the\nMessagePorts on that MessageChannel to the other thread through a\npre-existing channel, such as the global one.

\n

See port.postMessage() for more information on how messages are passed,\nand what kind of JavaScript values can be successfully transported through\nthe thread barrier.

\n
const assert = require('assert');\nconst {\n  Worker, MessageChannel, MessagePort, isMainThread, parentPort\n} = require('worker_threads');\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  const subChannel = new MessageChannel();\n  worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]);\n  subChannel.port2.on('message', (value) => {\n    console.log('received:', value);\n  });\n} else {\n  parentPort.once('message', (value) => {\n    assert(value.hereIsYourPort instanceof MessagePort);\n    value.hereIsYourPort.postMessage('the worker is sending this');\n    value.hereIsYourPort.close();\n  });\n}\n
", "events": [ { "textRaw": "Event: `'error'`", "type": "event", "name": "error", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "params": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" } ], "desc": "

The 'error' event is emitted if the worker thread throws an uncaught\nexception. In that case, the worker is terminated.

" }, { "textRaw": "Event: `'exit'`", "type": "event", "name": "exit", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "params": [ { "textRaw": "`exitCode` {integer}", "name": "exitCode", "type": "integer" } ], "desc": "

The 'exit' event is emitted once the worker has stopped. If the worker\nexited by calling process.exit(), the exitCode parameter is the\npassed exit code. If the worker was terminated, the exitCode parameter is\n1.

\n

This is the final event emitted by any Worker instance.

" }, { "textRaw": "Event: `'message'`", "type": "event", "name": "message", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "params": [ { "textRaw": "`value` {any} The transmitted value", "name": "value", "type": "any", "desc": "The transmitted value" } ], "desc": "

The 'message' event is emitted when the worker thread has invoked\nrequire('worker_threads').parentPort.postMessage().\nSee the port.on('message') event for more details.

\n

All messages sent from the worker thread are emitted before the\n'exit' event is emitted on the Worker object.

" }, { "textRaw": "Event: `'messageerror'`", "type": "event", "name": "messageerror", "meta": { "added": [ "v14.5.0", "v12.19.0" ], "changes": [] }, "params": [ { "textRaw": "`error` {Error} An Error object", "name": "error", "type": "Error", "desc": "An Error object" } ], "desc": "

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

" }, { "textRaw": "Event: `'online'`", "type": "event", "name": "online", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "params": [], "desc": "

The 'online' event is emitted when the worker thread has started executing\nJavaScript code.

" } ], "methods": [ { "textRaw": "`worker.getHeapSnapshot()`", "type": "method", "name": "getHeapSnapshot", "meta": { "added": [ "v13.9.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} A promise for a Readable Stream containing a V8 heap snapshot", "name": "return", "type": "Promise", "desc": "A promise for a Readable Stream containing a V8 heap snapshot" }, "params": [] } ], "desc": "

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

\n

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

" }, { "textRaw": "`worker.postMessage(value[, transferList])`", "type": "method", "name": "postMessage", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" }, { "textRaw": "`transferList` {Object[]}", "name": "transferList", "type": "Object[]" } ] } ], "desc": "

Send a message to the worker that is received via\nrequire('worker_threads').parentPort.on('message').\nSee port.postMessage() for more details.

" }, { "textRaw": "`worker.ref()`", "type": "method", "name": "ref", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

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

" }, { "textRaw": "`worker.terminate()`", "type": "method", "name": "terminate", "meta": { "added": [ "v10.5.0" ], "changes": [ { "version": "v12.5.0", "pr-url": "https://github.com/nodejs/node/pull/28021", "description": "This function now returns a Promise. Passing a callback is deprecated, and was useless up to this version, as the Worker was actually terminated synchronously. Terminating is now a fully asynchronous operation." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise}", "name": "return", "type": "Promise" }, "params": [] } ], "desc": "

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

" }, { "textRaw": "`worker.unref()`", "type": "method", "name": "unref", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

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

" } ], "properties": [ { "textRaw": "`worker.performance`", "name": "performance", "meta": { "added": [ "v15.1.0", "v12.22.0" ], "changes": [] }, "desc": "

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

", "methods": [ { "textRaw": "`performance.eventLoopUtilization([utilization1[, utilization2]])`", "type": "method", "name": "eventLoopUtilization", "meta": { "added": [ "v15.1.0", "v12.22.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns {Object}", "name": "return", "type": "Object", "options": [ { "textRaw": "`idle` {number}", "name": "idle", "type": "number" }, { "textRaw": "`active` {number}", "name": "active", "type": "number" }, { "textRaw": "`utilization` {number}", "name": "utilization", "type": "number" } ] }, "params": [ { "textRaw": "`utilization1` {Object} The result of a previous call to `eventLoopUtilization()`.", "name": "utilization1", "type": "Object", "desc": "The result of a previous call to `eventLoopUtilization()`." }, { "textRaw": "`utilization2` {Object} The result of a previous call to `eventLoopUtilization()` prior to `utilization1`.", "name": "utilization2", "type": "Object", "desc": "The result of a previous call to `eventLoopUtilization()` prior to `utilization1`." } ] } ], "desc": "

The same call as perf_hooks eventLoopUtilization(), except the values\nof the worker instance are returned.

\n

One difference is that, unlike the main thread, bootstrapping within a worker\nis done within the event loop. So the event loop utilization is\nimmediately available once the worker's script begins execution.

\n

An idle time that does not increase does not indicate that the worker is\nstuck in bootstrap. The following examples shows how the worker's entire\nlifetime never accumulates any idle time, but is still be able to process\nmessages.

\n
const { Worker, isMainThread, parentPort } = require('worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  setInterval(() => {\n    worker.postMessage('hi');\n    console.log(worker.performance.eventLoopUtilization());\n  }, 100).unref();\n  return;\n}\n\nparentPort.on('message', () => console.log('msg')).unref();\n(function r(n) {\n  if (--n < 0) return;\n  const t = Date.now();\n  while (Date.now() - t < 300);\n  setImmediate(r, n);\n})(10);\n
\n

The event loop utilization of a worker is available only after the 'online'\nevent emitted, and if called before this, or after the 'exit'\nevent, then all properties have the value of 0.

" } ] }, { "textRaw": "`resourceLimits` {Object}", "type": "Object", "name": "resourceLimits", "meta": { "added": [ "v13.2.0", "v12.16.0" ], "changes": [] }, "options": [ { "textRaw": "`maxYoungGenerationSizeMb` {number}", "name": "maxYoungGenerationSizeMb", "type": "number" }, { "textRaw": "`maxOldGenerationSizeMb` {number}", "name": "maxOldGenerationSizeMb", "type": "number" }, { "textRaw": "`codeRangeSizeMb` {number}", "name": "codeRangeSizeMb", "type": "number" }, { "textRaw": "`stackSizeMb` {number}", "name": "stackSizeMb", "type": "number" } ], "desc": "

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

\n

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

" }, { "textRaw": "`stderr` {stream.Readable}", "type": "stream.Readable", "name": "stderr", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "desc": "

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

" }, { "textRaw": "`stdin` {null|stream.Writable}", "type": "null|stream.Writable", "name": "stdin", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "desc": "

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

" }, { "textRaw": "`stdout` {stream.Readable}", "type": "stream.Readable", "name": "stdout", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "desc": "

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

" }, { "textRaw": "`threadId` {integer}", "type": "integer", "name": "threadId", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "desc": "

An integer identifier for the referenced thread. Inside the worker thread,\nit is available as require('worker_threads').threadId.\nThis value is unique for each Worker instance inside a single process.

" } ], "signatures": [ { "params": [ { "textRaw": "`filename` {string|URL} The path to the Worker’s main script or module. Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with `./` or `../`, or a WHATWG `URL` object using `file:` or `data:` protocol. When using a [`data:` URL][], the data is interpreted based on MIME type using the [ECMAScript module loader][]. If `options.eval` is `true`, this is a string containing JavaScript code rather than a path.", "name": "filename", "type": "string|URL", "desc": "The path to the Worker’s main script or module. Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with `./` or `../`, or a WHATWG `URL` object using `file:` or `data:` protocol. When using a [`data:` URL][], the data is interpreted based on MIME type using the [ECMAScript module loader][]. If `options.eval` is `true`, this is a string containing JavaScript code rather than a path." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`argv` {any[]} 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 are available on the global `process.argv` as if they were passed as CLI options to the script.", "name": "argv", "type": "any[]", "desc": "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 are available on the global `process.argv` as if they were passed as CLI options to the script." }, { "textRaw": "`env` {Object} If set, specifies the initial value of `process.env` inside the Worker thread. As a special value, [`worker.SHARE_ENV`][] may be used to specify that the parent thread and the child thread should share their environment variables; in that case, changes to one thread’s `process.env` object affect the other thread as well. **Default:** `process.env`.", "name": "env", "type": "Object", "default": "`process.env`", "desc": "If set, specifies the initial value of `process.env` inside the Worker thread. As a special value, [`worker.SHARE_ENV`][] may be used to specify that the parent thread and the child thread should share their environment variables; in that case, changes to one thread’s `process.env` object affect the other thread as well." }, { "textRaw": "`eval` {boolean} If `true` and the first argument is a `string`, interpret the first argument to the constructor as a script that is executed once the worker is online.", "name": "eval", "type": "boolean", "desc": "If `true` and the first argument is a `string`, interpret the first argument to the constructor as a script that is executed once the worker is online." }, { "textRaw": "`execArgv` {string[]} List of node CLI options passed to the worker. V8 options (such as `--max-old-space-size`) and options that affect the process (such as `--title`) are not supported. If set, this is provided as [`process.execArgv`][] inside the worker. By default, options are inherited from the parent thread.", "name": "execArgv", "type": "string[]", "desc": "List of node CLI options passed to the worker. V8 options (such as `--max-old-space-size`) and options that affect the process (such as `--title`) are not supported. If set, this is provided as [`process.execArgv`][] inside the worker. By default, options are inherited from the parent thread." }, { "textRaw": "`stdin` {boolean} If this is set to `true`, then `worker.stdin` provides a writable stream whose contents appear as `process.stdin` inside the Worker. By default, no data is provided.", "name": "stdin", "type": "boolean", "desc": "If this is set to `true`, then `worker.stdin` provides a writable stream whose contents appear as `process.stdin` inside the Worker. By default, no data is provided." }, { "textRaw": "`stdout` {boolean} If this is set to `true`, then `worker.stdout` is not automatically piped through to `process.stdout` in the parent.", "name": "stdout", "type": "boolean", "desc": "If this is set to `true`, then `worker.stdout` is not automatically piped through to `process.stdout` in the parent." }, { "textRaw": "`stderr` {boolean} If this is set to `true`, then `worker.stderr` is not automatically piped through to `process.stderr` in the parent.", "name": "stderr", "type": "boolean", "desc": "If this is set to `true`, then `worker.stderr` is not automatically piped through to `process.stderr` in the parent." }, { "textRaw": "`workerData` {any} Any JavaScript value that is cloned and made available as [`require('worker_threads').workerData`][]. The cloning occurs as described in the [HTML structured clone algorithm][], and an error is thrown if the object cannot be cloned (e.g. because it contains `function`s).", "name": "workerData", "type": "any", "desc": "Any JavaScript value that is cloned and made available as [`require('worker_threads').workerData`][]. The cloning occurs as described in the [HTML structured clone algorithm][], and an error is thrown if the object cannot be cloned (e.g. because it contains `function`s)." }, { "textRaw": "`trackUnmanagedFds` {boolean} If this is set to `true`, then the Worker tracks raw file descriptors managed through [`fs.open()`][] and [`fs.close()`][], and closes them when the Worker exits, similar to other resources like network sockets or file descriptors managed through the [`FileHandle`][] API. This option is automatically inherited by all nested `Worker`s. **Default:** `true`.", "name": "trackUnmanagedFds", "type": "boolean", "default": "`true`", "desc": "If this is set to `true`, then the Worker tracks raw file descriptors managed through [`fs.open()`][] and [`fs.close()`][], and closes them when the Worker exits, similar to other resources like network sockets or file descriptors managed through the [`FileHandle`][] API. This option is automatically inherited by all nested `Worker`s." }, { "textRaw": "`transferList` {Object[]} If one or more `MessagePort`-like objects are passed in `workerData`, a `transferList` is required for those items or [`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`][] is thrown. See [`port.postMessage()`][] for more information.", "name": "transferList", "type": "Object[]", "desc": "If one or more `MessagePort`-like objects are passed in `workerData`, a `transferList` is required for those items or [`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`][] is thrown. See [`port.postMessage()`][] for more information." }, { "textRaw": "`resourceLimits` {Object} An optional set of resource limits for the new JS engine instance. Reaching these limits leads to termination of the `Worker` instance. These limits only affect the JS engine, and no external data, including no `ArrayBuffer`s. Even if these limits are set, the process may still abort if it encounters a global out-of-memory situation.", "name": "resourceLimits", "type": "Object", "desc": "An optional set of resource limits for the new JS engine instance. Reaching these limits leads to termination of the `Worker` instance. These limits only affect the JS engine, and no external data, including no `ArrayBuffer`s. Even if these limits are set, the process may still abort if it encounters a global out-of-memory situation.", "options": [ { "textRaw": "`maxOldGenerationSizeMb` {number} The maximum size of the main heap in MB.", "name": "maxOldGenerationSizeMb", "type": "number", "desc": "The maximum size of the main heap in MB." }, { "textRaw": "`maxYoungGenerationSizeMb` {number} The maximum size of a heap space for recently created objects.", "name": "maxYoungGenerationSizeMb", "type": "number", "desc": "The maximum size of a heap space for recently created objects." }, { "textRaw": "`codeRangeSizeMb` {number} The size of a pre-allocated memory range used for generated code.", "name": "codeRangeSizeMb", "type": "number", "desc": "The size of a pre-allocated memory range used for generated code." }, { "textRaw": "`stackSizeMb` {number} The default maximum stack size for the thread. Small values may lead to unusable Worker instances. **Default:** `4`.", "name": "stackSizeMb", "type": "number", "default": "`4`", "desc": "The default maximum stack size for the thread. Small values may lead to unusable Worker instances." } ] } ] } ] } ] } ], "modules": [ { "textRaw": "Notes", "name": "notes", "modules": [ { "textRaw": "Synchronous blocking of stdio", "name": "synchronous_blocking_of_stdio", "desc": "

Workers utilize message passing via <MessagePort> to implement interactions\nwith stdio. This means that stdio output originating from a Worker can\nget blocked by synchronous code on the receiving end that is blocking the\nNode.js event loop.

\n
import {\n  Worker,\n  isMainThread,\n} from 'worker_threads';\n\nif (isMainThread) {\n  new Worker(new URL(import.meta.url));\n  for (let n = 0; n < 1e10; n++) {}\n} else {\n  // This output will be blocked by the for loop in the main thread.\n  console.log('foo');\n}\n
\n
'use strict';\n\nconst {\n  Worker,\n  isMainThread,\n} = require('worker_threads');\n\nif (isMainThread) {\n  new Worker(__filename);\n  for (let n = 0; n < 1e10; n++) {}\n} else {\n  // This output will be blocked by the for loop in the main thread.\n  console.log('foo');\n}\n
", "type": "module", "displayName": "Synchronous blocking of stdio" }, { "textRaw": "Launching worker threads from preload scripts", "name": "launching_worker_threads_from_preload_scripts", "desc": "

Take care when launching worker threads from preload scripts (scripts loaded\nand run using the -r command line flag). Unless the execArgv option is\nexplicitly set, new Worker threads automatically inherit the command line flags\nfrom the running process and will preload the same preload scripts as the main\nthread. If the preload script unconditionally launches a worker thread, every\nthread spawned will spawn another until the application crashes.

", "type": "module", "displayName": "Launching worker threads from preload scripts" } ], "type": "module", "displayName": "Notes" } ], "type": "module", "displayName": "Worker threads" } ] }