Usage
import * as mod from "node:worker_threads";
The node:worker_threads
module enables the use of threads that execute
JavaScript in parallel. To access it:
const worker = require('node:worker_threads');
Workers (threads) are useful for performing CPU-intensive JavaScript operations. They do not help much with I/O-intensive work. The Node.js built-in asynchronous I/O operations are more efficient than Workers can be.
Unlike child_process
or cluster
, worker_threads
can share memory. They do
so by transferring ArrayBuffer
instances or sharing SharedArrayBuffer
instances.
const { Worker, isMainThread, parentPort, workerData, } = require('node:worker_threads'); if (isMainThread) { module.exports = function parseJSAsync(script) { return new Promise((resolve, reject) => { const worker = new Worker(__filename, { workerData: script, }); worker.on('message', resolve); worker.on('error', reject); worker.on('exit', (code) => { if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`)); }); }); }; } else { const { parse } = require('some-js-parsing-library'); const script = workerData; parentPort.postMessage(parse(script)); }
The above example spawns a Worker thread for each parseJSAsync()
call. In
practice, use a pool of Workers for these kinds of tasks. Otherwise, the
overhead of creating Workers would likely exceed their benefit.
When implementing a worker pool, use the AsyncResource
API to inform
diagnostic tools (e.g. to provide asynchronous stack traces) about the
correlation between tasks and their outcomes. See "Using AsyncResource for a Worker thread pool"
in the async_hooks
documentation for an example implementation.
Worker threads inherit non-process-specific options by default. Refer to Worker constructor options
to know how to customize worker thread options,
specifically argv
and execArgv
options.
Instances of the worker.MessageChannel
class represent an asynchronous,
two-way communications channel.
The MessageChannel
has no methods of its own. new MessageChannel()
yields an object with port1
and port2
properties, which refer to linked MessagePort
instances.
Instances of the worker.MessagePort
class represent one end of an
asynchronous, two-way communications channel. It can be used to transfer
structured data, memory regions and other MessagePort
s between different Worker
s.
The Worker
class represents an independent JavaScript execution thread.
Most Node.js APIs are available inside of it.
Within a worker thread, worker.getEnvironmentData()
returns a clone
of data passed to the spawning thread's worker.setEnvironmentData()
.
Every new Worker
receives its own copy of the environment data
automatically.
Mark an object as not transferable. If object
occurs in the transfer list of
a port.postMessage()
call, it is ignored.
Transfer a MessagePort
to a different vm
Context. The original port
object is rendered unusable, and the returned MessagePort
instance
takes its place.
Receive a single message from a given MessagePort
. If no message is available,undefined
is returned, otherwise an object with a single message
property
that contains the message payload, corresponding to the oldest message in theMessagePort
's queue.
The worker.setEnvironmentData()
API sets the content ofworker.getEnvironmentData()
in the current thread and all new Worker
instances spawned from the current context.
Instances of BroadcastChannel
allow asynchronous one-to-many communication
with all other BroadcastChannel
instances bound to the same channel name.