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

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 will not help much with I/O-intensive work. Node.js’s built-in asynchronous\nI/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 instead for these kinds of tasks. Otherwise, the\noverhead of creating Workers would likely exceed their benefit.

", "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 was spawned as a Worker, this will be a MessagePort\nallowing communication with the parent thread. Messages sent using\nparentPort.postMessage() will be available in the parent thread\nusing worker.on('message'), and messages sent from the parent thread\nusing worker.postMessage() will be 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": "`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
" } ], "methods": [ { "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 which will be transferred.", "name": "port", "type": "MessagePort", "desc": "The message port which will be transferred." }, { "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 will be rendered unusable, and the returned MessagePort instance will\ntake its place.

\n

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

\n

However, the created MessagePort will no longer inherit from\nEventEmitter, 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": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object|undefined}", "name": "return", "type": "Object|undefined" }, "params": [ { "textRaw": "`port` {MessagePort}", "name": "port", "type": "MessagePort" } ] } ], "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 will be emitted and the\nonmessage listener will not be invoked.

" } ], "classes": [ { "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": [] }, "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

With the exception of MessagePorts being EventEmitters rather\nthan EventTargets, 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 will receive a clone of the value parameter as passed\nto postMessage() and no further arguments.

" } ], "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 will be 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": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" }, { "textRaw": "`transferList` {Object[]}", "name": "transferList", "type": "Object[]", "optional": true } ] } ], "desc": "

Sends a JavaScript value to the receiving side of this channel.\nvalue will be 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 and MessagePort objects.\nAfter transferring, they will not be 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 will be 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` will be 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

Because the object cloning uses the 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.

\n

The message object will be 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.

" }, { "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 will\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 will have no effect.

\n

If listeners are attached or removed using .on('message'), the port will\nbe 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 will be 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 will\nautomatically call .start(), but unsetting it will let 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 will allow 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 will have no effect.

\n

If listeners are attached or removed using .on('message'), the port will\nbe ref()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 will be 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 will be the\npassed exit code. If the worker was terminated, the exitCode parameter will\nbe 1.

" }, { "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.

" }, { "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.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[]", "optional": true } ] } ], "desc": "

Send a message to the worker that will be 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 will\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 will have\nno effect.

" }, { "textRaw": "worker.terminate([callback])", "type": "method", "name": "terminate", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`exitCode` {integer}", "name": "exitCode", "type": "integer" } ], "optional": true } ] } ], "desc": "

Stop all JavaScript execution in the worker thread as soon as possible.\ncallback is an optional function that is invoked once this operation is known\nto have completed.

\n

Warning: Currently, not all code in the internals of Node.js is prepared to\nexpect termination at arbitrary points in time and may crash if it encounters\nthat condition. Consequently, only call .terminate() if it is known that the\nWorker thread is not accessing Node.js core modules other than what is exposed\nin the worker module.

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

Calling unref() on a worker will allow 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 will have no effect.

" } ], "properties": [ { "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 will be 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 will be 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} The path to the Worker’s main script. Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with `./` or `../`. If `options.eval` is `true`, this is a string containing JavaScript code rather than a path.", "name": "filename", "type": "string", "desc": "The path to the Worker’s main script. Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with `./` or `../`. 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": "`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 will 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 will affect the other thread as well." }, { "textRaw": "`eval` {boolean} If `true`, 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`, 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 will be provided as [`process.execArgv`][] inside the worker. By default, options will be 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 will be provided as [`process.execArgv`][] inside the worker. By default, options will be inherited from the parent thread." }, { "textRaw": "`stdin` {boolean} If this is set to `true`, then `worker.stdin` will provide a writable stream whose contents will 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` will provide a writable stream whose contents will 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` will not automatically be piped through to `process.stdout` in the parent.", "name": "stdout", "type": "boolean", "desc": "If this is set to `true`, then `worker.stdout` will not automatically be piped through to `process.stdout` in the parent." }, { "textRaw": "`stderr` {boolean} If this is set to `true`, then `worker.stderr` will not automatically be piped through to `process.stderr` in the parent.", "name": "stderr", "type": "boolean", "desc": "If this is set to `true`, then `worker.stderr` will not automatically be piped through to `process.stderr` in the parent." }, { "textRaw": "`workerData` {any} Any JavaScript value that will be cloned and made available as [`require('worker_threads').workerData`][]. The cloning will occur as described in the [HTML structured clone algorithm][], and an error will be thrown if the object cannot be cloned (e.g. because it contains `function`s).", "name": "workerData", "type": "any", "desc": "Any JavaScript value that will be cloned and made available as [`require('worker_threads').workerData`][]. The cloning will occur as described in the [HTML structured clone algorithm][], and an error will be thrown if the object cannot be cloned (e.g. because it contains `function`s)." } ], "optional": true } ] } ] } ], "type": "module", "displayName": "Worker Threads" } ] }