Worker threads are stable and recommended for CPU-intensive JavaScript operations. For I/O-bound work, use Node.js’s built-in async operations instead.
Overview
Thenode:worker_threads module enables parallel execution of JavaScript. Workers are useful for performing CPU-intensive tasks without blocking the main event loop.
Key Differences from Other Concurrency Models
- vs child_process: Workers can share memory via
SharedArrayBufferand transferArrayBufferinstances - vs cluster: Workers share memory, cluster processes do not
- Use case: CPU-intensive JavaScript operations, not I/O
Worker Class
TheWorker class represents an independent JavaScript execution thread.
Constructor
new Worker(filename[, options])
Path to the Worker’s main script. Must be absolute or relative (starting with
./ or ../), or a WHATWG URL using file: or data: protocolConfiguration options
List of arguments stringified and appended to
process.argv in the workerEnvironment variables. Use
SHARE_ENV to share with parent. Default: process.envIf
true, interpret the first argument as a script to executeNode.js CLI options for the worker. Default: inherited from parent
If
true, worker.stdin provides a writable streamIf
true, worker.stdout is not piped to parentIf
true, worker.stderr is not piped to parentAny JavaScript value cloned and available as
workerData in the workerTrack raw file descriptors and close them when worker exits
If
MessagePort-like objects are in workerData, list them hereJS engine resource limits
Maximum size of main heap in MB
Maximum size of recently created objects heap in MB
Pre-allocated memory range for generated code
Default maximum stack size for the thread
Name for the worker (for debugging). Maximum sizes: Windows 32,767, macOS 64, Linux 16 characters
Events
Event: ‘error’
Event: ‘exit’
process.exit(), this is the exit code. If terminated, the code is 1.
Event: ‘message’
parentPort.postMessage().
Event: ‘messageerror’
Event: ‘online’
Emitted when the worker thread has started executing JavaScript code.Instance Methods
postMessage(value[, transferList])
Send a message to the worker thread.The value to send
List of
ArrayBuffer, MessagePort, and FileHandle objects to transferterminate()
Stops all JavaScript execution in the worker thread.Promise that resolves with the exit code
ref()
Opposite ofunref(). Keeps the event loop active while the worker is running.
unref()
Allows the thread to exit if this is the only active handle.getHeapSnapshot()
Returns a readable stream for a V8 heap snapshot of the worker.A readable stream containing the snapshot
Properties
threadId
Unique identifier for this worker thread
threadName
The name of the worker thread if running
resourceLimits
Resource limits for this worker
stdin, stdout, stderr
Writable/readable streams if the corresponding options were set.Module Functions
isMainThread
true if code is not running inside a Worker threadisInternalThread
true if running inside an internal Worker thread (e.g., loader thread)parentPort
MessagePort for communication with the parent thread.
null in the main threadthreadId
Integer identifier for the current thread
threadName
String identifier for the current thread, or null
workerData
Clone of the data passed to the Worker constructor
resourceLimits
JS engine resource constraints for this Worker. Empty object in main thread
SHARE_ENV
Special value for the
env option to share environment variablesEnvironment Data
setEnvironmentData(key[, value])
Sets data available to all new Worker instances.Any cloneable value usable as a Map key
Any cloneable value.
undefined deletes the keygetEnvironmentData(key)
Retrieves environment data set by the parent.The key to retrieve
The cloned data value
Transfer/Clone Functions
markAsUntransferable(object)
Marks an object as not transferable.Any arbitrary JavaScript value
isMarkedAsUntransferable(object)
Checks if an object is marked as untransferable.Any JavaScript value
true if marked as untransferablemarkAsUncloneable(object)
Marks an object as not cloneable.Any arbitrary JavaScript value
Thread Communication
postMessageToThread(threadId, value[, transferList][, timeout])
Sends a value to another worker by thread ID.The target thread ID
The value to send
Objects to transfer
Time to wait in milliseconds. Default: wait forever
Resolves when message is processed
MessageChannel & MessagePort
MessageChannel
Represents an asynchronous, two-way communications channel.MessagePort
One end of aMessageChannel. Extends EventTarget.
Events
close
Emitted once either side disconnects
message
Emitted for incoming messages. Receives the cloned value
messageerror
Emitted when deserializing fails
Methods
close()
Disables further sending of messages
postMessage(value[, transferList])
Sends a message to the receiving side
ref()
Keeps the event loop active
unref()
Allows the thread to exit
start()
Starts receiving messages (called automatically)
hasRef()
Returns
true if the port keeps the event loop activereceiveMessageOnPort(port)
Receives a single message synchronously.The port to receive from
{ message: value } or undefined if no message availableBroadcastChannel
Allows one-to-many communication with all otherBroadcastChannel instances.
Methods
close()
Closes the connection
postMessage(message)
Broadcasts a message to all channels with the same name
ref()
Keeps the event loop active
unref()
Allows the thread to exit
Properties
Invoked with a
MessageEvent when a message is receivedInvoked when a message cannot be deserialized
Lock Manager (Experimental)
locks.request(name[, options], callback)
Request a lock to coordinate resource access across threads.The name of the lock
Invoked once the lock is granted. Lock is released when function returns or promise settles
Resolves when the lock is released
locks.query()
Returns a snapshot of currently held and pending locks.Snapshot with
held and pending arraysData Transfer Considerations
Structured Clone Algorithm
Messages use the HTML structured clone algorithm:- ✅ Circular references supported
- ✅ Built-in types:
RegExp,BigInt,Map,Set - ✅ Typed arrays with
ArrayBufferandSharedArrayBuffer - ✅
WebAssembly.Moduleinstances - ✅ Specific Node.js types:
CryptoKey,FileHandle,MessagePort,X509Certificate - ❌ Native C++ objects (except listed above)
TypedArrays and Buffers
Be careful when transferringArrayBuffers:
Classes and Prototypes
Object cloning doesn’t preserve:- Non-enumerable properties
- Property accessors
- Object prototypes
- Private fields
Best Practices
Worker Pool PatternDon’t spawn a Worker for each task - use a pool! The overhead of creating Workers exceeds their benefit for small tasks.
Async TrackingWhen implementing worker pools, use
AsyncResource for proper async stack traces.