- Assertion Testing
- Async Hooks
- Buffer
- C++ Addons
- C/C++ Addons with N-API
- Child Processes
- Cluster
- Command Line Options
- Console
- Crypto
- Debugger
- Deprecated APIs
- DNS
- Domain
- ECMAScript Modules
- Errors
- Events
- File System
- Globals
- HTTP
- HTTP/2
- HTTPS
- Inspector
- Internationalization
- Modules
- Net
- OS
- Path
- Performance Hooks
- Policies
- Process
- Punycode
- Query Strings
- Readline
- REPL
- Report
- Stream
- String Decoder
- Timers
- TLS/SSL
- Trace Events
- TTY
- UDP/Datagram
- URL
- Utilities
- V8
- VM
- WASI
- Worker Threads
- Zlib
Node.js v13.14.0 Documentation
Table of Contents
Worker Threads#
The worker_threads module enables the use of threads that execute JavaScript
in parallel. To access it:
const worker = require('worker_threads');
Workers (threads) are useful for performing CPU-intensive JavaScript operations. They will not help much with I/O-intensive work. Node.js’s 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('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 parse() call. In actual
practice, use a pool of Workers instead 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. in order 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.
worker.isMainThread#
Is true if this code is not running inside of a Worker thread.
const { Worker, isMainThread } = require('worker_threads');
if (isMainThread) {
// This re-loads the current file inside a Worker instance.
new Worker(__filename);
} else {
console.log('Inside Worker!');
console.log(isMainThread); // Prints 'false'.
}
worker.moveMessagePortToContext(port, contextifiedSandbox)#
-
port<MessagePort> The message port which will be transferred. -
contextifiedSandbox<Object> A contextified object as returned by thevm.createContext()method. -
Returns: <MessagePort>
Transfer a MessagePort to a different vm Context. The original port