Node.js Reference ยท child_process, worker_threads and cluster
The Node.js Worker class
Reference for the worker_threads Worker class in Node.js: constructor options, events, postMessage(), terminate(), threadId, stdio, resource limits and error handling.
A Worker runs a JavaScript file in a separate thread of the same process. The worker has its own V8 isolate, event loop and module cache, so CPU-heavy work there never blocks the main thread's event loop. The two sides communicate by messages that are copied (or transferred, or shared); they do not share variables.
You create a worker with new Worker(filename, options) from node:worker_threads and talk to it through worker.postMessage() and the 'message' event. Inside the worker, the matching pieces are parentPort, workerData and isMainThread. A worker is lighter than a child process: it starts in a few milliseconds and shares the process's memory space, but it does not isolate crashes from native code.
import { Worker } from 'node:worker_threads'; const worker = new Worker('./job.mjs', { workerData: { n: 10 } }); worker.on('message', (value) => console.log('result', value)); worker.on('error', (error) => console.error(error)); worker.on('exit', (code) => console.log('exit', code));
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
new Worker(filename[, options])
| Name | Description |
|---|---|
filename |
Path of the script: an absolute path, or a relative path that starts with ./ or ../, or a file: URL (for example new URL('./w.js', import.meta.url)). With eval: true it is a string of code instead. |
options.workerData |
Any cloneable value, copied to the worker and available there as workerData. See workerData. |
options.eval |
If true, filename is JavaScript source (run as a CommonJS script). |
options.argv |
Extra values appended to process.argv in the worker. |
options.env |
Environment object for the worker. Default: a copy of the parent's process.env. Pass SHARE_ENV to share the live object. |
options.execArgv |
Node flags for the worker. Defaults to the parent's flags. |
options.stdin, stdout, stderr |
stdin: true gives the worker a writable stream you feed with worker.stdin. stdout: true or stderr: true stop the output from being piped to the parent's streams and let you read worker.stdout and worker.stderr instead. |
options.resourceLimits |
Memory and stack limits (see resourceLimits). |
options.transferList |
Objects (such as ArrayBuffer or MessagePort) moved into the worker with workerData. See Transferring memory. |
options.trackUnmanagedFds |
Close file descriptors opened by the worker when it exits. Default true. |
Events: 'online' (the worker started running JavaScript), 'message' (the worker called postMessage), 'messageerror' (a message could not be deserialized), 'error' (an uncaught exception in the worker), 'exit' (the thread ended; the argument is the exit code, which is 1 after an uncaught error or terminate()).
Methods and properties: postMessage(value[, transferList]), terminate() (returns a promise for the exit code), ref(), unref(), threadId (a number, -1 once the worker has exited), resourceLimits, performance.eventLoopUtilization(), getHeapSnapshot(), and the streams stdin, stdout, stderr.
Errors: an invalid filename (not absolute, not starting with ./, or a bare name) throws ERR_WORKER_PATH synchronously. Errors thrown inside the worker never throw in the parent; they arrive as the 'error' event.
Usage notes
- Always handle
'error'. An uncaught exception in the worker ends it and is delivered as'error'. Without a listener the event is thrown in the parent and can crash the process. 'exit'always comes last, after any'error'. Use it for cleanup and for the exit code.- Messages are cloned, using the structured clone algorithm: objects, arrays,
Map,Set,Date, typed arrays,Errorand more, but not functions or class instances' methods. LargeArrayBuffers can be transferred instead of copied. - A worker keeps the process alive while it runs and has listeners on its port. Call
worker.unref()for background helpers, or close the port from the worker. terminate()stops JavaScript immediately, even awhile (true)loop. It does not runfinallyblocks, and in-flight messages may be lost. Prefer asking the worker to finish by message.- Each worker has its own heap. Creating hundreds is wasteful; reuse them with a worker pool.
process.exit()inside a worker ends only that worker, not the process.process.chdir()and signal handlers are not available there.- Worker versus child process. Workers can share memory (
SharedArrayBuffer) and start faster; child processes isolate crashes and can run other programs.