Worker

external class Worker : EventEmitter(source)

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, and process.stderr streams may be redirected by the parent thread.

  • The require('node:worker_threads').isMainThread property is set to false.

  • The require('node:worker_threads').parentPort message port is available.

  • process.exit() does not stop the whole program, just the single thread, and process.abort() is not available.

  • process.chdir() and process 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 (unless worker.SHARE_ENV is passed as the env option to the Worker 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 Workers 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 theMessagePorts 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

Constructors

Link copied to clipboard
constructor(filename: String, options: WorkerOptions = definedExternally)
constructor(filename: URL, options: WorkerOptions = definedExternally)

Properties

Link copied to clipboard

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

Link copied to clipboard

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.

Link copied to clipboard

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

Link copied to clipboard

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

Link copied to clipboard

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

Link copied to clipboard

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

Functions

Link copied to clipboard
fun addListener(event: Symbol, listener: Function<Unit>)
fun addListener(event: String, listener: Function<Unit>)
fun addListener(event: WorkerEvent.ERROR, listener: (JsError) -> Unit)
fun addListener(event: WorkerEvent.EXIT, listener: (exitCode: Double) -> Unit)
fun addListener(event: WorkerEvent.MESSAGE, listener: (value: Any?) -> Unit)
fun addListener(event: WorkerEvent.MESSAGEERROR, listener: (JsError) -> Unit)
fun addListener(event: WorkerEvent.ONLINE, listener: () -> Unit)
Link copied to clipboard
fun emit(event: Symbol, vararg args: Any?): Boolean
fun emit(event: String, vararg args: Any?): Boolean
fun emit(event: WorkerEvent.EXIT, exitCode: Number): Boolean
fun emit(event: WorkerEvent.MESSAGE, value: Any?): Boolean
Link copied to clipboard

Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or Symbols.

Link copied to clipboard

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

Link copied to clipboard

Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to {@link defaultMaxListeners}.

Link copied to clipboard
fun off(event: Symbol, listener: Function<Unit>)
fun off(event: String, listener: Function<Unit>)
fun off(event: WorkerEvent.ERROR, listener: (JsError) -> Unit)
fun off(event: WorkerEvent.EXIT, listener: (exitCode: Double) -> Unit)
fun off(event: WorkerEvent.MESSAGE, listener: (value: Any?) -> Unit)
fun off(event: WorkerEvent.MESSAGEERROR, listener: (JsError) -> Unit)
fun off(event: WorkerEvent.ONLINE, listener: () -> Unit)
Link copied to clipboard
fun on(event: Symbol, listener: Function<Unit>)
fun on(event: String, listener: Function<Unit>)
fun on(event: WorkerEvent.ERROR, listener: (JsError) -> Unit)
fun on(event: WorkerEvent.EXIT, listener: (exitCode: Double) -> Unit)
fun on(event: WorkerEvent.MESSAGE, listener: (value: Any?) -> Unit)
fun on(event: WorkerEvent.MESSAGEERROR, listener: (JsError) -> Unit)
fun on(event: WorkerEvent.ONLINE, listener: () -> Unit)
Link copied to clipboard
fun once(event: Symbol, listener: Function<Unit>)
fun once(event: String, listener: Function<Unit>)
fun once(event: WorkerEvent.ERROR, listener: (JsError) -> Unit)
fun once(event: WorkerEvent.EXIT, listener: (exitCode: Double) -> Unit)
fun once(event: WorkerEvent.MESSAGE, listener: (value: Any?) -> Unit)
fun once(event: WorkerEvent.MESSAGEERROR, listener: (JsError) -> Unit)
fun once(event: WorkerEvent.ONLINE, listener: () -> Unit)
Link copied to clipboard
fun postMessage(value: Any?, transferList: ReadonlyArray<TransferListItem> = definedExternally)

Send a message to the worker that is received via require('node:worker_threads').parentPort.on('message'). See port.postMessage() for more details.

Link copied to clipboard
fun postMessageToThread(threadId: Number, value: Any?, timeout: Number = definedExternally): Promise<Void>

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

fun postMessageToThread(threadId: Number, value: Any?, transferList: ReadonlyArray<TransferListItem>, timeout: Number = definedExternally): Promise<Void>
Link copied to clipboard
fun prependListener(event: Symbol, listener: Function<Unit>)
fun prependListener(event: String, listener: Function<Unit>)
fun prependListener(event: WorkerEvent.ERROR, listener: (JsError) -> Unit)
fun prependListener(event: WorkerEvent.EXIT, listener: (exitCode: Double) -> Unit)
fun prependListener(event: WorkerEvent.MESSAGE, listener: (value: Any?) -> Unit)
fun prependListener(event: WorkerEvent.ONLINE, listener: () -> Unit)
Link copied to clipboard
fun prependOnceListener(event: Symbol, listener: Function<Unit>)
fun prependOnceListener(event: String, listener: Function<Unit>)
fun prependOnceListener(event: WorkerEvent.EXIT, listener: (exitCode: Double) -> Unit)
fun prependOnceListener(event: WorkerEvent.MESSAGE, listener: (value: Any?) -> Unit)
fun prependOnceListener(event: WorkerEvent.ONLINE, listener: () -> Unit)
Link copied to clipboard
fun ref()

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

Link copied to clipboard
fun removeListener(event: Symbol, listener: Function<Unit>)
fun removeListener(event: String, listener: Function<Unit>)
fun removeListener(event: WorkerEvent.ERROR, listener: (JsError) -> Unit)
fun removeListener(event: WorkerEvent.EXIT, listener: (exitCode: Double) -> Unit)
fun removeListener(event: WorkerEvent.MESSAGE, listener: (value: Any?) -> Unit)
fun removeListener(event: WorkerEvent.ONLINE, listener: () -> Unit)
Link copied to clipboard

By default EventEmitters 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.

Link copied to clipboard

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

Link copied to clipboard
fun unref()

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