Worker
The Worker
class represents an independent JavaScript execution thread. Most Node.js APIs are available inside of it.
Notable differences inside a Worker environment are:
The
process.stdin
,process.stdout
, andprocess.stderr
streams may be redirected by the parent thread.The
require('node:worker_threads').isMainThread
property is set tofalse
.The
require('node:worker_threads').parentPort
message port is available.process.exit()
does not stop the whole program, just the single thread, andprocess.abort()
is not available.process.chdir()
andprocess
methods that set group or user ids are not available.process.env
is a copy of the parent thread's environment variables, unless otherwise specified. Changes to one copy are not visible in other threads, and are not visible to native add-ons (unlessworker.SHARE_ENV
is passed as theenv
option to theWorker
constructor). On Windows, unlike the main thread, a copy of the environment variables operates in a case-sensitive manner.process.title
cannot be modified.Signals are not delivered through
process.on('...')
.Execution may stop at any point as a result of
worker.terminate()
being invoked.IPC channels from parent processes are not accessible.
The
trace_events
module is not supported.Native add-ons can only be loaded from multiple threads if they fulfill
certain conditions
.
Creating Worker
instances inside of other Worker
s is possible.
Like Web Workers and the node:cluster module
, two-way communication can be achieved through inter-thread message passing. Internally, a Worker
has a built-in pair of MessagePort
s that are already associated with each other when the Worker
is created. While the MessagePort
object on the parent side is not directly exposed, its functionalities are exposed through worker.postMessage()
and the worker.on('message')
event on the Worker
object for the parent thread.
To create custom messaging channels (which is encouraged over using the default global channel because it facilitates separation of concerns), users can create a MessageChannel
object on either thread and pass one of theMessagePort
s on that MessageChannel
to the other thread through a pre-existing channel, such as the global one.
See port.postMessage()
for more information on how messages are passed, and what kind of JavaScript values can be successfully transported through the thread barrier.
const assert = require('node:assert');
const {
Worker, MessageChannel, MessagePort, isMainThread, parentPort,
} = require('node:worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
const subChannel = new MessageChannel();
worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]);
subChannel.port2.on('message', (value) => {
console.log('received:', value);
});
} else {
parentPort.once('message', (value) => {
assert(value.hereIsYourPort instanceof MessagePort);
value.hereIsYourPort.postMessage('the worker is sending this');
value.hereIsYourPort.close();
});
}
Since
v10.5.0
Properties
An object that can be used to query performance information from a worker instance. Similar to perf_hooks.performance
.
Provides the set of JS engine resource constraints for this Worker thread. If the resourceLimits
option was passed to the Worker
constructor, this matches its values.
Functions
Alias for emitter.on(eventName, listener)
.
Synchronously calls each of the listeners registered for the event named eventName
, in the order they were registered, passing the supplied arguments to each.
Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or Symbol
s.
Returns a readable stream for a V8 snapshot of the current state of the Worker. See v8.getHeapSnapshot()
for more details.
Returns the current max listener value for the EventEmitter
which is either set by emitter.setMaxListeners(n)
or defaults to {@link defaultMaxListeners}.
Returns the number of listeners listening for the event named eventName
. If listener
is provided, it will return how many times the listener is found in the list of the listeners of the event.
Returns a copy of the array of listeners for the event named eventName
.
Adds the listener
function to the end of the listeners array for the event named eventName
. No checks are made to see if the listener
has already been added. Multiple calls passing the same combination of eventName
and listener
will result in the listener
being added, and called, multiple times.
Send a message to the worker that is received via require('node:worker_threads').parentPort.on('message')
. See port.postMessage()
for more details.
Sends a value to another worker, identified by its thread ID.
Adds the listener
function to the beginning of the listeners array for the event named eventName
. No checks are made to see if the listener
has already been added. Multiple calls passing the same combination of eventName
and listener
will result in the listener
being added, and called, multiple times.
Adds a one-timelistener
function for the event named eventName
to the beginning of the listeners array. The next time eventName
is triggered, this listener is removed, and then invoked.
Returns a copy of the array of listeners for the event named eventName
, including any wrappers (such as those created by .once()
).
Removes all listeners, or those of the specified eventName
.
Removes the specified listener
from the listener array for the event named eventName
.
By default EventEmitter
s will print a warning if more than 10
listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners()
method allows the limit to be modified for this specific EventEmitter
instance. The value can be set to Infinity
(or 0
) to indicate an unlimited number of listeners.