Offload CPU-intensive computation
A server must perform expensive calculations without blocking its event loop.
Node.js · Module
node:worker_threads runs JavaScript in parallel in independent threads, making it suitable for CPU-intensive work. Workers communicate through message ports and can transfer or share memory buffers.
The node:worker_threads module provides independent JavaScript execution threads for parallel work. A Worker communicates with its parent through message ports, while ArrayBuffer objects can be transferred and SharedArrayBuffer objects can be shared.
new Worker(filename[, options])| Name | Type | Description |
|---|---|---|
filename | string | URL | Worker entry-point filename; the current documentation describes it as a path or URL identifying the worker's main script. |
options | object | Optional Worker configuration, including execution and resource settings. |
new Worker() returns a Worker instance representing the newly created execution thread.
import { Worker, isMainThread, parentPort } from 'node:worker_threads';
if (isMainThread) {
const worker = new Worker(new URL(import.meta.url));
worker.once('message', (result) => console.log(result));
worker.postMessage(21);
} else {
parentPort.once('message', (value) => parentPort.postMessage(value * 2));
}The main thread starts a worker from the same module, sends it a value, and prints the worker's response.
A server must perform expensive calculations without blocking its event loop.
Several worker threads need asynchronous bidirectional messaging.
Large binary data must cross thread boundaries efficiently.
A worker needs access to standard Node.js functionality while running independently.
The module creates independent JavaScript execution threads, primarily for CPU-intensive operations. It is less useful for I/O because Node's asynchronous I/O is more efficient for that workload.
Follow-up: How can workers exchange data? Through message ports, transferring ArrayBuffer instances, or sharing SharedArrayBuffer instances.
A Worker is an independent JavaScript execution thread. The parent and worker communicate with postMessage-style message events through the worker's communication port.
Follow-up: What object represents a two-way message channel? MessageChannel creates two connected MessagePort instances.
ArrayBuffer instances can be transferred between threads, while SharedArrayBuffer instances can be shared. This permits data exchange without treating the worker like a child process.
Follow-up: What should be considered when sharing memory? Synchronization and coordination are required because multiple threads can access shared data.
WorkerMessageChannelMessagePortparentPortisMainThreadisInternalThreadthreadIdworkerData