{ "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
module provides a way to create multiple environments running\non independent threads, and to create message channels between them. It\ncan be accessed using the --experimental-worker
flag and:
const worker = require('worker_threads');\n
\nWorkers are useful for performing CPU-intensive JavaScript operations; do not\nuse them for I/O, since Node.js’s built-in mechanisms for performing operations\nasynchronously already treat it more efficiently than Worker threads can.
\nWorkers, unlike child processes or when using the cluster
module, can also\nshare memory efficiently by transferring ArrayBuffer
instances or sharing\nSharedArrayBuffer
instances between them.
const {\n Worker, isMainThread, parentPort, workerData\n} = require('worker_threads');\n\nif (isMainThread) {\n module.exports = async 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
\nNote that this example spawns a Worker thread for each parse
call.\nIn practice, it is strongly recommended to use a pool of Workers for these\nkinds of tasks, since the overhead of creating Workers would likely exceed the\nbenefit of handing the work off to it.
Is true
if this code is not running inside of a Worker
thread.
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')
.
An integer identifier for the current thread. On the corresponding worker object\n(if there is any), it is available as worker.threadId
.
An arbitrary JavaScript value that contains a clone of the data passed\nto this thread’s Worker
constructor.
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.
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": "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 MessagePort
s between different\nWorker
s.
With the exception of MessagePort
s being EventEmitter
s rather\nthan EventTarget
s, this implementation matches browser MessagePort
s.
The 'close'
event is emitted once either side of the channel has been\ndisconnected.
The 'message'
event is emitted for any incoming message, containing the cloned\ninput of port.postMessage()
.
Listeners on this event will receive a clone of the value
parameter as passed\nto postMessage()
and no further arguments.
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
.
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. In particular, it may contain circular\nreferences and objects like typed arrays that the JSON
API is not able\nto stringify.
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.
If value
contains SharedArrayBuffer
instances, those will be accessible\nfrom either thread. They cannot be listed in transferList
.
value
may still contain ArrayBuffer
instances that are not in\ntransferList
; in that case, the underlying memory is copied rather than moved.
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 Uint8Array
s on the receiving side.
The message object will be cloned immediately, and can be modified after\nposting without having side effects.
\nFor more information on the serialization and deserialization mechanisms\nbehind this API, see the serialization API of the v8
module.
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.
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.
Starts receiving messages on this MessagePort
. When using this port\nas an event emitter, this will be called automatically once 'message'
\nlisteners are attached.
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.
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.
The Worker
class represents an independent JavaScript execution thread.\nMost Node.js APIs are available inside of it.
Notable differences inside a Worker environment are:
\nprocess.stdin
, process.stdout
and process.stderr
\nmay be redirected by the parent thread.require('worker_threads').isMainThread
property is set to false
.require('worker_threads').parentPort
message port is available.process.exit()
does not stop the whole program, just the single thread,\nand process.abort()
is not available.process.chdir()
and process
methods that set group or user ids\nare not available.process.env
is a read-only reference to the environment variables.process.title
cannot be modified.process.on('...')
.worker.terminate()
\nbeing invoked.Currently, the following differences also exist until they are addressed:
\ninspector
module is not available yet.Creating Worker
instances inside of other Worker
s is possible.
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 MessagePort
s 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.
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\nMessagePort
s on that MessageChannel
to the other thread through a\npre-existing channel, such as the global one.
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.
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.
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
.
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.
The 'online'
event is emitted when the worker thread has started executing\nJavaScript code.
Send a message to the worker that will be received via\nrequire('worker_threads').parentPort.on('message')
.\nSee port.postMessage()
for more details.
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.
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.
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.
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.
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.
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
.
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.
An integer identifier for the referenced thread. Inside the worker thread,\nit is available as require('worker_threads').threadId
.