The getHeapSnapshot method is not supported.
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.stderrstreams may be redirected by the parent thread. - The
import { isMainThread } from 'node:worker_threads'variable is set tofalse. - The
import { parentPort } from 'node:worker_threads'message port is available. process.exit()does not stop the whole program, just the single thread, andprocess.abort()is not available.process.chdir()andprocessmethods that set group or user ids are not available.process.envis 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_ENVis passed as theenvoption to theWorkerconstructor). On Windows, unlike the main thread, a copy of the environment variables operates in a case-sensitive manner.process.titlecannot 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_eventsmodule 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.
import assert from 'node:assert';
import {
Worker, MessageChannel, MessagePort, isMainThread, parentPort,
} from '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();
});
}
Constructors Jump to heading
Jump to headingWorker(filename: string | URL,options?: WorkerOptions,)Properties Jump to heading
An object that can be used to query performance information from a worker
instance. Similar to perf_hooks.performance.
Jump to headingresourceLimits: ResourceLimits | undefinedProvides 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.
If the worker has stopped, the return value is an empty object.
Jump to headingstderr: ReadableThis 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.
Jump to headingstdin: Writable | nullIf 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.
Jump to headingstdout: ReadableThis 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.
Jump to headingthreadId: numberAn integer identifier for the referenced thread. Inside the worker thread,
it is available as import { threadId } from 'node:worker_threads'.
This value is unique for each Worker instance inside a single process.
Methods Jump to heading
Jump to headingaddListener(event: "error",listener: (err: Error) => void,): thisJump to headingaddListener(event: "exit",listener: (exitCode: number) => void,): thisJump to headingaddListener(event: "message",listener: (value: any) => void,): thisJump to headingaddListener(event: "messageerror",listener: (error: Error) => void,): thisJump to headingaddListener(event: "online",listener: () => void,): thisJump to headingaddListener(event: string | symbol,listener: (...args: any[]) => void,): thisJump to headingemit(event: "error",err: Error,): booleanJump to headingemit(event: "exit",exitCode: number,): booleanJump to headingemit(event: "message",value: any,): booleanJump to headingemit(event: "messageerror",error: Error,): booleanJump to headingemit(event: "online"): booleanJump to headingemit(event: string | symbol,...args: any[],): booleanJump to headinggetHeapSnapshot(): Promise<Readable>Returns a readable stream for a V8 snapshot of the current state of the Worker.
See v8.getHeapSnapshot() for more details.
If the Worker thread is no longer running, which may occur before the 'exit' event is emitted, the returned Promise is rejected
immediately with an ERR_WORKER_NOT_RUNNING error.
Jump to headingoff(event: "error",listener: (err: Error) => void,): thisJump to headingoff(event: "exit",listener: (exitCode: number) => void,): thisJump to headingoff(event: "message",listener: (value: any) => void,): thisJump to headingoff(event: "messageerror",listener: (error: Error) => void,): thisJump to headingoff(event: "online",listener: () => void,): thisJump to headingoff(event: string | symbol,listener: (...args: any[]) => void,): thisJump to headingon(event: "error",listener: (err: Error) => void,): thisJump to headingon(event: "exit",listener: (exitCode: number) => void,): thisJump to headingon(event: "message",listener: (value: any) => void,): thisJump to headingon(event: "messageerror",listener: (error: Error) => void,): thisJump to headingon(event: "online",listener: () => void,): thisJump to headingon(event: string | symbol,listener: (...args: any[]) => void,): thisJump to headingonce(event: "error",listener: (err: Error) => void,): thisJump to headingonce(event: "exit",listener: (exitCode: number) => void,): thisJump to headingonce(event: "message",listener: (value: any) => void,): thisJump to headingonce(event: "messageerror",listener: (error: Error) => void,): thisJump to headingonce(event: "online",listener: () => void,): thisJump to headingonce(event: string | symbol,listener: (...args: any[]) => void,): thisJump to headingpostMessage(value: any,transferList?: readonly TransferListItem[],): voidSend a message to the worker that is received via require('node:worker_threads').parentPort.on('message').
See port.postMessage() for more details.
Jump to headingpostMessageToThread(threadId: number,value: any,timeout?: number,): Promise<void>Sends a value to another worker, identified by its thread ID.
Jump to headingpostMessageToThread(): Promise<void>Jump to headingprependListener(event: "error",listener: (err: Error) => void,): thisJump to headingprependListener(event: "exit",listener: (exitCode: number) => void,): thisJump to headingprependListener(event: "message",listener: (value: any) => void,): thisJump to headingprependListener(event: "messageerror",listener: (error: Error) => void,): thisJump to headingprependListener(event: "online",listener: () => void,): thisJump to headingprependListener(event: string | symbol,listener: (...args: any[]) => void,): thisJump to headingprependOnceListener(event: "error",listener: (err: Error) => void,): thisJump to headingprependOnceListener(event: "exit",listener: (exitCode: number) => void,): thisJump to headingprependOnceListener(event: "message",listener: (value: any) => void,): thisJump to headingprependOnceListener(event: "messageerror",listener: (error: Error) => void,): thisJump to headingprependOnceListener(event: "online",listener: () => void,): thisJump to headingprependOnceListener(event: string | symbol,listener: (...args: any[]) => void,): thisJump to headingref(): voidOpposite 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.
Jump to headingremoveListener(event: "error",listener: (err: Error) => void,): thisJump to headingremoveListener(event: "exit",listener: (exitCode: number) => void,): thisJump to headingremoveListener(event: "message",listener: (value: any) => void,): thisJump to headingremoveListener(event: "messageerror",listener: (error: Error) => void,): thisJump to headingremoveListener(event: "online",listener: () => void,): thisJump to headingremoveListener(event: string | symbol,listener: (...args: any[]) => void,): thisJump to headingterminate(): Promise<number>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.
Jump to headingunref(): voidCalling 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.