D7net
Home
Console
Upload
information
Create File
Create Folder
About
Tools
:
/
opt
/
alt
/
alt-nodejs12
/
root
/
usr
/
share
/
doc
/
alt-nodejs12-nodejs-12.22.9
/
html
/
api
/
Filename :
worker_threads.html
back
Copy
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <meta name="nodejs.org:node-version" content="v12.22.9"> <title>Worker threads | Node.js v12.22.9 Documentation</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback"> <link rel="stylesheet" href="assets/style.css"> <link rel="stylesheet" href="assets/hljs.css"> <link rel="canonical" href="https://nodejs.org/api/worker_threads.html"> </head> <body class="alt apidoc" id="api-section-worker_threads"> <div id="content" class="clearfix"> <div id="column2" class="interior"> <div id="intro" class="interior"> <a href="/" title="Go back to the home page"> Node.js </a> </div> <ul> <li><a href="documentation.html" class="nav-documentation">About this documentation</a></li> <li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li> </ul> <hr class="line"> <ul> <li><a href="assert.html" class="nav-assert">Assertion testing</a></li> <li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li> <li><a href="buffer.html" class="nav-buffer">Buffer</a></li> <li><a href="addons.html" class="nav-addons">C++ Addons</a></li> <li><a href="n-api.html" class="nav-n-api">C/C++ Addons with N-API</a></li> <li><a href="embedding.html" class="nav-embedding">C++ Embedder API</a></li> <li><a href="child_process.html" class="nav-child_process">Child Processes</a></li> <li><a href="cluster.html" class="nav-cluster">Cluster</a></li> <li><a href="cli.html" class="nav-cli">Command line options</a></li> <li><a href="console.html" class="nav-console">Console</a></li> <li><a href="crypto.html" class="nav-crypto">Crypto</a></li> <li><a href="debugger.html" class="nav-debugger">Debugger</a></li> <li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> <li><a href="dns.html" class="nav-dns">DNS</a></li> <li><a href="domain.html" class="nav-domain">Domain</a></li> <li><a href="errors.html" class="nav-errors">Errors</a></li> <li><a href="events.html" class="nav-events">Events</a></li> <li><a href="fs.html" class="nav-fs">File system</a></li> <li><a href="globals.html" class="nav-globals">Globals</a></li> <li><a href="http.html" class="nav-http">HTTP</a></li> <li><a href="http2.html" class="nav-http2">HTTP/2</a></li> <li><a href="https.html" class="nav-https">HTTPS</a></li> <li><a href="inspector.html" class="nav-inspector">Inspector</a></li> <li><a href="intl.html" class="nav-intl">Internationalization</a></li> <li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li> <li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li> <li><a href="module.html" class="nav-module">Modules: <code>module</code> API</a></li> <li><a href="packages.html" class="nav-packages">Modules: Packages</a></li> <li><a href="net.html" class="nav-net">Net</a></li> <li><a href="os.html" class="nav-os">OS</a></li> <li><a href="path.html" class="nav-path">Path</a></li> <li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li> <li><a href="policy.html" class="nav-policy">Policies</a></li> <li><a href="process.html" class="nav-process">Process</a></li> <li><a href="punycode.html" class="nav-punycode">Punycode</a></li> <li><a href="querystring.html" class="nav-querystring">Query strings</a></li> <li><a href="readline.html" class="nav-readline">Readline</a></li> <li><a href="repl.html" class="nav-repl">REPL</a></li> <li><a href="report.html" class="nav-report">Report</a></li> <li><a href="stream.html" class="nav-stream">Stream</a></li> <li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li> <li><a href="timers.html" class="nav-timers">Timers</a></li> <li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> <li><a href="tracing.html" class="nav-tracing">Trace events</a></li> <li><a href="tty.html" class="nav-tty">TTY</a></li> <li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li> <li><a href="url.html" class="nav-url">URL</a></li> <li><a href="util.html" class="nav-util">Utilities</a></li> <li><a href="v8.html" class="nav-v8">V8</a></li> <li><a href="vm.html" class="nav-vm">VM</a></li> <li><a href="wasi.html" class="nav-wasi">WASI</a></li> <li><a href="worker_threads.html" class="nav-worker_threads active">Worker threads</a></li> <li><a href="zlib.html" class="nav-zlib">Zlib</a></li> </ul> <hr class="line"> <ul> <li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li> </ul> </div> <div id="column1" data-id="worker_threads" class="interior"> <header> <h1>Node.js v12.22.9 Documentation</h1> <div id="gtoc"> <ul> <li> <a href="index.html">Index</a> </li> <li> <a href="all.html">View on single page</a> </li> <li> <a href="worker_threads.json">View as JSON</a> </li> <li class="version-picker"> <a href="#">View another version <span>▼</span></a> <ol class="version-picker"><li><a href="https://nodejs.org/docs/latest-v17.x/api/worker_threads.html">17.x</a></li> <li><a href="https://nodejs.org/docs/latest-v16.x/api/worker_threads.html">16.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v15.x/api/worker_threads.html">15.x</a></li> <li><a href="https://nodejs.org/docs/latest-v14.x/api/worker_threads.html">14.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v13.x/api/worker_threads.html">13.x</a></li> <li><a href="https://nodejs.org/docs/latest-v12.x/api/worker_threads.html">12.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v11.x/api/worker_threads.html">11.x</a></li> <li><a href="https://nodejs.org/docs/latest-v10.x/api/worker_threads.html">10.x</a></li></ol> </li> <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/master/doc/api/worker_threads.md"><span class="github_icon"><svg height="16" width="16" viewBox="0 0 16.1 16.1" fill="currentColor"><path d="M8 0a8 8 0 0 0-2.5 15.6c.4 0 .5-.2.5-.4v-1.5c-2 .4-2.5-.5-2.7-1 0-.1-.5-.9-.8-1-.3-.2-.7-.6 0-.6.6 0 1 .6 1.2.8.7 1.2 1.9 1 2.4.7 0-.5.2-.9.5-1-1.8-.3-3.7-1-3.7-4 0-.9.3-1.6.8-2.2 0-.2-.3-1 .1-2 0 0 .7-.3 2.2.7a7.4 7.4 0 0 1 4 0c1.5-1 2.2-.8 2.2-.8.5 1.1.2 2 .1 2.1.5.6.8 1.3.8 2.2 0 3-1.9 3.7-3.6 4 .3.2.5.7.5 1.4v2.2c0 .2.1.5.5.4A8 8 0 0 0 16 8a8 8 0 0 0-8-8z"/></svg></span>Edit on GitHub</a></li> </ul> </div> <hr> </header> <div id="toc"> <h2>Table of Contents</h2> <ul> <li><span class="stability_2"><a href="#worker_threads_worker_threads">Worker threads</a></span> <ul> <li><a href="#worker_threads_worker_ismainthread"><code>worker.isMainThread</code></a></li> <li><a href="#worker_threads_worker_markasuntransferable_object"><code>worker.markAsUntransferable(object)</code></a></li> <li><a href="#worker_threads_worker_movemessageporttocontext_port_contextifiedsandbox"><code>worker.moveMessagePortToContext(port, contextifiedSandbox)</code></a></li> <li><a href="#worker_threads_worker_parentport"><code>worker.parentPort</code></a></li> <li><a href="#worker_threads_worker_receivemessageonport_port"><code>worker.receiveMessageOnPort(port)</code></a></li> <li><a href="#worker_threads_worker_resourcelimits"><code>worker.resourceLimits</code></a></li> <li><a href="#worker_threads_worker_share_env"><code>worker.SHARE_ENV</code></a></li> <li><a href="#worker_threads_worker_threadid"><code>worker.threadId</code></a></li> <li><a href="#worker_threads_worker_workerdata"><code>worker.workerData</code></a></li> <li><a href="#worker_threads_class_messagechannel">Class: <code>MessageChannel</code></a></li> <li><a href="#worker_threads_class_messageport">Class: <code>MessagePort</code></a> <ul> <li><a href="#worker_threads_event_close">Event: <code>'close'</code></a></li> <li><a href="#worker_threads_event_message">Event: <code>'message'</code></a></li> <li><a href="#worker_threads_event_messageerror">Event: <code>'messageerror'</code></a></li> <li><a href="#worker_threads_port_close"><code>port.close()</code></a></li> <li><a href="#worker_threads_port_postmessage_value_transferlist"><code>port.postMessage(value[, transferList])</code></a> <ul> <li><a href="#worker_threads_considerations_when_transferring_typedarrays_and_buffers">Considerations when transferring TypedArrays and Buffers</a></li> </ul> </li> <li><a href="#worker_threads_port_ref"><code>port.ref()</code></a></li> <li><a href="#worker_threads_port_start"><code>port.start()</code></a></li> <li><a href="#worker_threads_port_unref"><code>port.unref()</code></a></li> </ul> </li> <li><a href="#worker_threads_class_worker">Class: <code>Worker</code></a> <ul> <li><a href="#worker_threads_new_worker_filename_options"><code>new Worker(filename[, options])</code></a></li> <li><a href="#worker_threads_event_error">Event: <code>'error'</code></a></li> <li><a href="#worker_threads_event_exit">Event: <code>'exit'</code></a></li> <li><a href="#worker_threads_event_message_1">Event: <code>'message'</code></a></li> <li><a href="#worker_threads_event_messageerror_1">Event: <code>'messageerror'</code></a></li> <li><a href="#worker_threads_event_online">Event: <code>'online'</code></a></li> <li><a href="#worker_threads_worker_getheapsnapshot"><code>worker.getHeapSnapshot()</code></a></li> <li><a href="#worker_threads_worker_performance"><code>worker.performance</code></a> <ul> <li><a href="#worker_threads_performance_eventlooputilization_utilization1_utilization2"><code>performance.eventLoopUtilization([utilization1[, utilization2]])</code></a></li> </ul> </li> <li><a href="#worker_threads_worker_postmessage_value_transferlist"><code>worker.postMessage(value[, transferList])</code></a></li> <li><a href="#worker_threads_worker_ref"><code>worker.ref()</code></a></li> <li><a href="#worker_threads_worker_resourcelimits_1"><code>worker.resourceLimits</code></a></li> <li><a href="#worker_threads_worker_stderr"><code>worker.stderr</code></a></li> <li><a href="#worker_threads_worker_stdin"><code>worker.stdin</code></a></li> <li><a href="#worker_threads_worker_stdout"><code>worker.stdout</code></a></li> <li><a href="#worker_threads_worker_terminate"><code>worker.terminate()</code></a></li> <li><a href="#worker_threads_worker_threadid_1"><code>worker.threadId</code></a></li> <li><a href="#worker_threads_worker_unref"><code>worker.unref()</code></a></li> </ul> </li> </ul> </li> </ul> </div> <div id="apicontent"> <h1>Worker threads<span><a class="mark" href="#worker_threads_worker_threads" id="worker_threads_worker_threads">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v12.22.9/lib/worker_threads.js">lib/worker_threads.js</a></p> <p>The <code>worker_threads</code> module enables the use of threads that execute JavaScript in parallel. To access it:</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> worker = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);</code></pre> <p>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.</p> <p>Unlike <code>child_process</code> or <code>cluster</code>, <code>worker_threads</code> can share memory. They do so by transferring <code>ArrayBuffer</code> instances or sharing <code>SharedArrayBuffer</code> instances.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> { Worker, isMainThread, parentPort, workerData } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>); <span class="hljs-keyword">if</span> (isMainThread) { <span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">parseJSAsync</span>(<span class="hljs-params">script</span>) </span>{ <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> { <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> Worker(__filename, { <span class="hljs-attr">workerData</span>: script }); worker.on(<span class="hljs-string">'message'</span>, resolve); worker.on(<span class="hljs-string">'error'</span>, reject); worker.on(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> { <span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</span>) reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`Worker stopped with exit code <span class="hljs-subst">${code}</span>`</span>)); }); }); }; } <span class="hljs-keyword">else</span> { <span class="hljs-keyword">const</span> { parse } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'some-js-parsing-library'</span>); <span class="hljs-keyword">const</span> script = workerData; parentPort.postMessage(parse(script)); }</code></pre> <p>The above example spawns a Worker thread for each <code>parse()</code> 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.</p> <p>When implementing a worker pool, use the <a href="async_hooks.html#async_hooks_class_asyncresource"><code>AsyncResource</code></a> API to inform diagnostic tools (e.g. in order to provide asynchronous stack traces) about the correlation between tasks and their outcomes. See <a href="async_hooks.html#async-resource-worker-pool">"Using <code>AsyncResource</code> for a <code>Worker</code> thread pool"</a> in the <code>async_hooks</code> documentation for an example implementation.</p> <p>Worker threads inherit non-process-specific options by default. Refer to <a href="#worker_threads_new_worker_filename_options"><code>Worker constructor options</code></a> to know how to customize worker thread options, specifically <code>argv</code> and <code>execArgv</code> options.</p> <h2><code>worker.isMainThread</code><span><a class="mark" href="#worker_threads_worker_ismainthread" id="worker_threads_worker_ismainthread">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Is <code>true</code> if this code is not running inside of a <a href="#worker_threads_class_worker"><code>Worker</code></a> thread.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> { Worker, isMainThread } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>); <span class="hljs-keyword">if</span> (isMainThread) { <span class="hljs-comment">// This re-loads the current file inside a Worker instance.</span> <span class="hljs-keyword">new</span> Worker(__filename); } <span class="hljs-keyword">else</span> { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Inside Worker!'</span>); <span class="hljs-built_in">console</span>.log(isMainThread); <span class="hljs-comment">// Prints 'false'.</span> }</code></pre> <h2><code>worker.markAsUntransferable(object)</code><span><a class="mark" href="#worker_threads_worker_markasuntransferable_object" id="worker_threads_worker_markasuntransferable_object">#</a></span></h2> <div class="api_metadata"> <span>Added in: v12.19.0</span> </div> <p>Mark an object as not transferable. If <code>object</code> occurs in the transfer list of a <a href="#worker_threads_port_postmessage_value_transferlist"><code>port.postMessage()</code></a> call, it will be ignored.</p> <p>In particular, this makes sense for objects that can be cloned, rather than transferred, and which are used by other objects on the sending side. For example, Node.js marks the <code>ArrayBuffer</code>s it uses for its <a href="buffer.html#buffer_static_method_buffer_allocunsafe_size"><code>Buffer</code> pool</a> with this.</p> <p>This operation cannot be undone.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> { MessageChannel, markAsUntransferable } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>); <span class="hljs-keyword">const</span> pooledBuffer = <span class="hljs-keyword">new</span> <span class="hljs-built_in">ArrayBuffer</span>(<span class="hljs-number">8</span>); <span class="hljs-keyword">const</span> typedArray1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Uint8Array</span>(pooledBuffer); <span class="hljs-keyword">const</span> typedArray2 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Float64Array</span>(pooledBuffer); markAsUntransferable(pooledBuffer); <span class="hljs-keyword">const</span> { port1 } = <span class="hljs-keyword">new</span> MessageChannel(); port1.postMessage(typedArray1, [ typedArray1.buffer ]); <span class="hljs-comment">// The following line prints the contents of typedArray1 -- it still owns</span> <span class="hljs-comment">// its memory and has been cloned, not transferred. Without</span> <span class="hljs-comment">// `markAsUntransferable()`, this would print an empty Uint8Array.</span> <span class="hljs-comment">// typedArray2 is intact as well.</span> <span class="hljs-built_in">console</span>.log(typedArray1); <span class="hljs-built_in">console</span>.log(typedArray2);</code></pre> <p>There is no equivalent to this API in browsers.</p> <h2><code>worker.moveMessagePortToContext(port, contextifiedSandbox)</code><span><a class="mark" href="#worker_threads_worker_movemessageporttocontext_port_contextifiedsandbox" id="worker_threads_worker_movemessageporttocontext_port_contextifiedsandbox">#</a></span></h2> <div class="api_metadata"> <span>Added in: v11.13.0</span> </div> <ul> <li> <p><code>port</code> <a href="worker_threads.html#worker_threads_class_messageport" class="type"><MessagePort></a> The message port which will be transferred.</p> </li> <li> <p><code>contextifiedSandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A <a href="vm.html#vm_what_does_it_mean_to_contextify_an_object">contextified</a> object as returned by the <code>vm.createContext()</code> method.</p> </li> <li> <p>Returns: <a href="worker_threads.html#worker_threads_class_messageport" class="type"><MessagePort></a></p> </li> </ul> <p>Transfer a <code>MessagePort</code> to a different <a href="vm.html"><code>vm</code></a> Context. The original <code>port</code> object will be rendered unusable, and the returned <code>MessagePort</code> instance will take its place.</p> <p>The returned <code>MessagePort</code> will be an object in the target context, and will inherit from its global <code>Object</code> class. Objects passed to the <a href="https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage"><code>port.onmessage()</code></a> listener will also be created in the target context and inherit from its global <code>Object</code> class.</p> <p>However, the created <code>MessagePort</code> will no longer inherit from <a href="events.html"><code>EventEmitter</code></a>, and only <a href="https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage"><code>port.onmessage()</code></a> can be used to receive events using it.</p> <h2><code>worker.parentPort</code><span><a class="mark" href="#worker_threads_worker_parentport" id="worker_threads_worker_parentport">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> | <a href="worker_threads.html#worker_threads_class_messageport" class="type"><MessagePort></a></li> </ul> <p>If this thread was spawned as a <a href="#worker_threads_class_worker"><code>Worker</code></a>, this will be a <a href="#worker_threads_class_messageport"><code>MessagePort</code></a> allowing communication with the parent thread. Messages sent using <code>parentPort.postMessage()</code> will be available in the parent thread using <code>worker.on('message')</code>, and messages sent from the parent thread using <code>worker.postMessage()</code> will be available in this thread using <code>parentPort.on('message')</code>.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> { Worker, isMainThread, parentPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>); <span class="hljs-keyword">if</span> (isMainThread) { <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> Worker(__filename); worker.once(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> { <span class="hljs-built_in">console</span>.log(message); <span class="hljs-comment">// Prints 'Hello, world!'.</span> }); worker.postMessage(<span class="hljs-string">'Hello, world!'</span>); } <span class="hljs-keyword">else</span> { <span class="hljs-comment">// When a message from the parent thread is received, send it back:</span> parentPort.once(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> { parentPort.postMessage(message); }); }</code></pre> <h2><code>worker.receiveMessageOnPort(port)</code><span><a class="mark" href="#worker_threads_worker_receivemessageonport_port" id="worker_threads_worker_receivemessageonport_port">#</a></span></h2> <div class="api_metadata"> <span>Added in: v12.3.0</span> </div> <ul> <li> <p><code>port</code> <a href="worker_threads.html#worker_threads_class_messageport" class="type"><MessagePort></a></p> </li> <li> <p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></p> </li> </ul> <p>Receive a single message from a given <code>MessagePort</code>. If no message is available, <code>undefined</code> is returned, otherwise an object with a single <code>message</code> property that contains the message payload, corresponding to the oldest message in the <code>MessagePort</code>’s queue.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> { MessageChannel, receiveMessageOnPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>); <span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> MessageChannel(); port1.postMessage({ <span class="hljs-attr">hello</span>: <span class="hljs-string">'world'</span> }); <span class="hljs-built_in">console</span>.log(receiveMessageOnPort(port2)); <span class="hljs-comment">// Prints: { message: { hello: 'world' } }</span> <span class="hljs-built_in">console</span>.log(receiveMessageOnPort(port2)); <span class="hljs-comment">// Prints: undefined</span></code></pre> <p>When this function is used, no <code>'message'</code> event will be emitted and the <code>onmessage</code> listener will not be invoked.</p> <h2><code>worker.resourceLimits</code><span><a class="mark" href="#worker_threads_worker_resourcelimits" id="worker_threads_worker_resourcelimits">#</a></span></h2> <div class="api_metadata"> <span>Added in: v12.16.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <li><code>maxYoungGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>maxOldGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>codeRangeSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>stackSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> </li> </ul> <p>Provides the set of JS engine resource constraints inside this Worker thread. If the <code>resourceLimits</code> option was passed to the <a href="#worker_threads_class_worker"><code>Worker</code></a> constructor, this matches its values.</p> <p>If this is used in the main thread, its value is an empty object.</p> <h2><code>worker.SHARE_ENV</code><span><a class="mark" href="#worker_threads_worker_share_env" id="worker_threads_worker_share_env">#</a></span></h2> <div class="api_metadata"> <span>Added in: v11.14.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></li> </ul> <p>A special value that can be passed as the <code>env</code> option of the <a href="#worker_threads_class_worker"><code>Worker</code></a> constructor, to indicate that the current thread and the Worker thread should share read and write access to the same set of environment variables.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> { Worker, SHARE_ENV } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>); <span class="hljs-keyword">new</span> Worker(<span class="hljs-string">'process.env.SET_IN_WORKER = "foo"'</span>, { <span class="hljs-attr">eval</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">env</span>: SHARE_ENV }) .on(<span class="hljs-string">'exit'</span>, <span class="hljs-function">() =></span> { <span class="hljs-built_in">console</span>.log(process.env.SET_IN_WORKER); <span class="hljs-comment">// Prints 'foo'.</span> });</code></pre> <h2><code>worker.threadId</code><span><a class="mark" href="#worker_threads_worker_threadid" id="worker_threads_worker_threadid">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>An integer identifier for the current thread. On the corresponding worker object (if there is any), it is available as <a href="#worker_threads_worker_threadid_1"><code>worker.threadId</code></a>. This value is unique for each <a href="#worker_threads_class_worker"><code>Worker</code></a> instance inside a single process.</p> <h2><code>worker.workerData</code><span><a class="mark" href="#worker_threads_worker_workerdata" id="worker_threads_worker_workerdata">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>An arbitrary JavaScript value that contains a clone of the data passed to this thread’s <code>Worker</code> constructor.</p> <p>The data is cloned as if using <a href="#worker_threads_port_postmessage_value_transferlist"><code>postMessage()</code></a>, according to the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> { Worker, isMainThread, workerData } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>); <span class="hljs-keyword">if</span> (isMainThread) { <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> Worker(__filename, { <span class="hljs-attr">workerData</span>: <span class="hljs-string">'Hello, world!'</span> }); } <span class="hljs-keyword">else</span> { <span class="hljs-built_in">console</span>.log(workerData); <span class="hljs-comment">// Prints 'Hello, world!'.</span> }</code></pre> <h2>Class: <code>MessageChannel</code><span><a class="mark" href="#worker_threads_class_messagechannel" id="worker_threads_class_messagechannel">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>Instances of the <code>worker.MessageChannel</code> class represent an asynchronous, two-way communications channel. The <code>MessageChannel</code> has no methods of its own. <code>new MessageChannel()</code> yields an object with <code>port1</code> and <code>port2</code> properties, which refer to linked <a href="#worker_threads_class_messageport"><code>MessagePort</code></a> instances.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> { MessageChannel } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>); <span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> MessageChannel(); port1.on(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'received'</span>, message)); port2.postMessage({ <span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span> }); <span class="hljs-comment">// Prints: received { foo: 'bar' } from the `port1.on('message')` listener</span></code></pre> <h2>Class: <code>MessagePort</code><span><a class="mark" href="#worker_threads_class_messageport" id="worker_threads_class_messageport">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li>Extends: <a href="events.html#events_class_eventemitter" class="type"><EventEmitter></a></li> </ul> <p>Instances of the <code>worker.MessagePort</code> class represent one end of an asynchronous, two-way communications channel. It can be used to transfer structured data, memory regions and other <code>MessagePort</code>s between different <a href="#worker_threads_class_worker"><code>Worker</code></a>s.</p> <p>With the exception of <code>MessagePort</code>s being <a href="events.html"><code>EventEmitter</code></a>s rather than <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget"><code>EventTarget</code></a>s, this implementation matches <a href="https://developer.mozilla.org/en-US/docs/Web/API/MessagePort">browser <code>MessagePort</code></a>s.</p> <h3>Event: <code>'close'</code><span><a class="mark" href="#worker_threads_event_close" id="worker_threads_event_close">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>The <code>'close'</code> event is emitted once either side of the channel has been disconnected.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> { MessageChannel } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>); <span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> MessageChannel(); <span class="hljs-comment">// Prints:</span> <span class="hljs-comment">// foobar</span> <span class="hljs-comment">// closed!</span> port2.on(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-built_in">console</span>.log(message)); port2.on(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'closed!'</span>)); port1.postMessage(<span class="hljs-string">'foobar'</span>); port1.close();</code></pre> <h3>Event: <code>'message'</code><span><a class="mark" href="#worker_threads_event_message" id="worker_threads_event_message">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The transmitted value</li> </ul> <p>The <code>'message'</code> event is emitted for any incoming message, containing the cloned input of <a href="#worker_threads_port_postmessage_value_transferlist"><code>port.postMessage()</code></a>.</p> <p>Listeners on this event will receive a clone of the <code>value</code> parameter as passed to <code>postMessage()</code> and no further arguments.</p> <h3>Event: <code>'messageerror'</code><span><a class="mark" href="#worker_threads_event_messageerror" id="worker_threads_event_messageerror">#</a></span></h3> <div class="api_metadata"> <span>Added in: v12.19.0</span> </div> <ul> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> An Error object</li> </ul> <p>The <code>'messageerror'</code> event is emitted when deserializing a message failed.</p> <h3><code>port.close()</code><span><a class="mark" href="#worker_threads_port_close" id="worker_threads_port_close">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>Disables further sending of messages on either side of the connection. This method can be called when no further communication will happen over this <code>MessagePort</code>.</p> <p>The <a href="#worker_threads_event_close"><code>'close'</code> event</a> will be emitted on both <code>MessagePort</code> instances that are part of the channel.</p> <h3><code>port.postMessage(value[, transferList])</code><span><a class="mark" href="#worker_threads_port_postmessage_value_transferlist" id="worker_threads_port_postmessage_value_transferlist">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v12.19.0</td> <td><p>Added <code>KeyObject</code> to the list of cloneable types.</p></td></tr> <tr><td>v12.19.0</td> <td><p>Added <code>FileHandle</code> to the list of transferable types.</p></td></tr> <tr><td>v10.5.0</td> <td><p><span>Added in: v10.5.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li> </ul> <p>Sends a JavaScript value to the receiving side of this channel. <code>value</code> will be transferred in a way which is compatible with the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>.</p> <p>In particular, the significant differences to <code>JSON</code> are:</p> <ul> <li><code>value</code> may contain circular references.</li> <li><code>value</code> may contain instances of builtin JS types such as <code>RegExp</code>s, <code>BigInt</code>s, <code>Map</code>s, <code>Set</code>s, etc.</li> <li><code>value</code> may contain typed arrays, both using <code>ArrayBuffer</code>s and <code>SharedArrayBuffer</code>s.</li> <li><code>value</code> may contain <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module"><code>WebAssembly.Module</code></a> instances.</li> <li><code>value</code> may not contain native (C++-backed) objects other than <code>MessagePort</code>s, <a href="fs.html#fs_class_filehandle"><code>FileHandle</code></a>s, and <a href="crypto.html#crypto_class_keyobject"><code>KeyObject</code></a>s.</li> </ul> <pre><code class="language-js"><span class="hljs-keyword">const</span> { MessageChannel } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>); <span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> MessageChannel(); port1.on(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-built_in">console</span>.log(message)); <span class="hljs-keyword">const</span> circularData = {}; circularData.foo = circularData; <span class="hljs-comment">// Prints: { foo: [Circular] }</span> port2.postMessage(circularData);</code></pre> <p><code>transferList</code> may be a list of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>, <a href="#worker_threads_class_messageport"><code>MessagePort</code></a> and <a href="fs.html#fs_class_filehandle"><code>FileHandle</code></a> objects. After transferring, they will not be usable on the sending side of the channel anymore (even if they are not contained in <code>value</code>). Unlike with <a href="child_process.html">child processes</a>, transferring handles such as network sockets is currently not supported.</p> <p>If <code>value</code> contains <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> instances, those will be accessible from either thread. They cannot be listed in <code>transferList</code>.</p> <p><code>value</code> may still contain <code>ArrayBuffer</code> instances that are not in <code>transferList</code>; in that case, the underlying memory is copied rather than moved.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> { MessageChannel } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>); <span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> MessageChannel(); port1.on(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-built_in">console</span>.log(message)); <span class="hljs-keyword">const</span> uint8Array = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Uint8Array</span>([ <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span> ]); <span class="hljs-comment">// This posts a copy of `uint8Array`:</span> port2.postMessage(uint8Array); <span class="hljs-comment">// This does not copy data, but renders `uint8Array` unusable:</span> port2.postMessage(uint8Array, [ uint8Array.buffer ]); <span class="hljs-comment">// The memory for the `sharedUint8Array` will be accessible from both the</span> <span class="hljs-comment">// original and the copy received by `.on('message')`:</span> <span class="hljs-keyword">const</span> sharedUint8Array = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Uint8Array</span>(<span class="hljs-keyword">new</span> SharedArrayBuffer(<span class="hljs-number">4</span>)); port2.postMessage(sharedUint8Array); <span class="hljs-comment">// This transfers a freshly created message port to the receiver.</span> <span class="hljs-comment">// This can be used, for example, to create communication channels between</span> <span class="hljs-comment">// multiple `Worker` threads that are children of the same parent thread.</span> <span class="hljs-keyword">const</span> otherChannel = <span class="hljs-keyword">new</span> MessageChannel(); port2.postMessage({ <span class="hljs-attr">port</span>: otherChannel.port1 }, [ otherChannel.port1 ]);</code></pre> <p>Because the object cloning uses the structured clone algorithm, non-enumerable properties, property accessors, and object prototypes are not preserved. In particular, <a href="buffer.html"><code>Buffer</code></a> objects will be read as plain <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a>s on the receiving side.</p> <p>The message object will be cloned immediately, and can be modified after posting without having side effects.</p> <p>For more information on the serialization and deserialization mechanisms behind this API, see the <a href="v8.html#v8_serialization_api">serialization API of the <code>v8</code> module</a>.</p> <h4>Considerations when transferring TypedArrays and Buffers<span><a class="mark" href="#worker_threads_considerations_when_transferring_typedarrays_and_buffers" id="worker_threads_considerations_when_transferring_typedarrays_and_buffers">#</a></span></h4> <p>All <code>TypedArray</code> and <code>Buffer</code> instances are views over an underlying <code>ArrayBuffer</code>. That is, it is the <code>ArrayBuffer</code> that actually stores the raw data while the <code>TypedArray</code> and <code>Buffer</code> objects provide a way of viewing and manipulating the data. It is possible and common for multiple views to be created over the same <code>ArrayBuffer</code> instance. Great care must be taken when using a transfer list to transfer an <code>ArrayBuffer</code> as doing so will cause all <code>TypedArray</code> and <code>Buffer</code> instances that share that same <code>ArrayBuffer</code> to become unusable.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> ab = <span class="hljs-keyword">new</span> <span class="hljs-built_in">ArrayBuffer</span>(<span class="hljs-number">10</span>); <span class="hljs-keyword">const</span> u1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Uint8Array</span>(ab); <span class="hljs-keyword">const</span> u2 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Uint16Array</span>(ab); <span class="hljs-built_in">console</span>.log(u2.length); <span class="hljs-comment">// prints 5</span> port.postMessage(u1, [u1.buffer]); <span class="hljs-built_in">console</span>.log(u2.length); <span class="hljs-comment">// prints 0</span></code></pre> <p>For <code>Buffer</code> instances, specifically, whether the underlying <code>ArrayBuffer</code> can be transferred or cloned depends entirely on how instances were created, which often cannot be reliably determined.</p> <p>An <code>ArrayBuffer</code> can be marked with <a href="#worker_threads_worker_markasuntransferable_object"><code>markAsUntransferable()</code></a> to indicate that it should always be cloned and never transferred.</p> <p>Depending on how a <code>Buffer</code> instance was created, it may or may not own its underlying <code>ArrayBuffer</code>. An <code>ArrayBuffer</code> must not be transferred unless it is known that the <code>Buffer</code> instance owns it. In particular, for <code>Buffer</code>s created from the internal <code>Buffer</code> pool (using, for instance <code>Buffer.from()</code> or <code>Buffer.alloc()</code>), transferring them is not possible and they will always be cloned, which sends a copy of the entire <code>Buffer</code> pool. This behavior may come with unintended higher memory usage and possible security concerns.</p> <p>See <a href="buffer.html#buffer_static_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe()</code></a> for more details on <code>Buffer</code> pooling.</p> <p>The <code>ArrayBuffer</code>s for <code>Buffer</code> instances created using <code>Buffer.alloc()</code> or <code>Buffer.allocUnsafeSlow()</code> can always be transferred but doing so will render all other existing views of those <code>ArrayBuffer</code>s unusable.</p> <h3><code>port.ref()</code><span><a class="mark" href="#worker_threads_port_ref" id="worker_threads_port_ref">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>Opposite of <code>unref()</code>. Calling <code>ref()</code> on a previously <code>unref()</code>ed port will <em>not</em> let the program exit if it's the only active handle left (the default behavior). If the port is <code>ref()</code>ed, calling <code>ref()</code> again will have no effect.</p> <p>If listeners are attached or removed using <code>.on('message')</code>, the port will be <code>ref()</code>ed and <code>unref()</code>ed automatically depending on whether listeners for the event exist.</p> <h3><code>port.start()</code><span><a class="mark" href="#worker_threads_port_start" id="worker_threads_port_start">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>Starts receiving messages on this <code>MessagePort</code>. When using this port as an event emitter, this will be called automatically once <code>'message'</code> listeners are attached.</p> <p>This method exists for parity with the Web <code>MessagePort</code> API. In Node.js, it is only useful for ignoring messages when no event listener is present. Node.js also diverges in its handling of <code>.onmessage</code>. Setting it will automatically call <code>.start()</code>, but unsetting it will let messages queue up until a new handler is set or the port is discarded.</p> <h3><code>port.unref()</code><span><a class="mark" href="#worker_threads_port_unref" id="worker_threads_port_unref">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>Calling <code>unref()</code> on a port will allow the thread to exit if this is the only active handle in the event system. If the port is already <code>unref()</code>ed calling <code>unref()</code> again will have no effect.</p> <p>If listeners are attached or removed using <code>.on('message')</code>, the port will be <code>ref()</code>ed and <code>unref()</code>ed automatically depending on whether listeners for the event exist.</p> <h2>Class: <code>Worker</code><span><a class="mark" href="#worker_threads_class_worker" id="worker_threads_class_worker">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li>Extends: <a href="events.html#events_class_eventemitter" class="type"><EventEmitter></a></li> </ul> <p>The <code>Worker</code> class represents an independent JavaScript execution thread. Most Node.js APIs are available inside of it.</p> <p>Notable differences inside a Worker environment are:</p> <ul> <li>The <a href="process.html#process_process_stdin"><code>process.stdin</code></a>, <a href="process.html#process_process_stdout"><code>process.stdout</code></a> and <a href="process.html#process_process_stderr"><code>process.stderr</code></a> may be redirected by the parent thread.</li> <li>The <a href="#worker_threads_worker_ismainthread"><code>require('worker_threads').isMainThread</code></a> property is set to <code>false</code>.</li> <li>The <a href="#worker_threads_worker_parentport"><code>require('worker_threads').parentPort</code></a> message port is available.</li> <li><a href="process.html#process_process_exit_code"><code>process.exit()</code></a> does not stop the whole program, just the single thread, and <a href="process.html#process_process_abort"><code>process.abort()</code></a> is not available.</li> <li><a href="process.html#process_process_chdir_directory"><code>process.chdir()</code></a> and <code>process</code> methods that set group or user ids are not available.</li> <li><a href="process.html#process_process_env"><code>process.env</code></a> is a copy of the parent thread's environment variables, unless otherwise specified. Changes to one copy will not be visible in other threads, and will not be visible to native add-ons (unless <a href="#worker_threads_worker_share_env"><code>worker.SHARE_ENV</code></a> has been passed as the <code>env</code> option to the <a href="#worker_threads_class_worker"><code>Worker</code></a> constructor).</li> <li><a href="process.html#process_process_title"><code>process.title</code></a> cannot be modified.</li> <li>Signals will not be delivered through <a href="process.html#process_signal_events"><code>process.on('...')</code></a>.</li> <li>Execution may stop at any point as a result of <a href="#worker_threads_worker_terminate"><code>worker.terminate()</code></a> being invoked.</li> <li>IPC channels from parent processes are not accessible.</li> <li>The <a href="tracing.html"><code>trace_events</code></a> module is not supported.</li> <li>Native add-ons can only be loaded from multiple threads if they fulfill <a href="addons.html#addons_worker_support">certain conditions</a>.</li> </ul> <p>Creating <code>Worker</code> instances inside of other <code>Worker</code>s is possible.</p> <p>Like <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">Web Workers</a> and the <a href="cluster.html"><code>cluster</code> module</a>, two-way communication can be achieved through inter-thread message passing. Internally, a <code>Worker</code> has a built-in pair of <a href="#worker_threads_class_messageport"><code>MessagePort</code></a>s that are already associated with each other when the <code>Worker</code> is created. While the <code>MessagePort</code> object on the parent side is not directly exposed, its functionalities are exposed through <a href="#worker_threads_worker_postmessage_value_transferlist"><code>worker.postMessage()</code></a> and the <a href="#worker_threads_event_message_1"><code>worker.on('message')</code></a> event on the <code>Worker</code> object for the parent thread.</p> <p>To create custom messaging channels (which is encouraged over using the default global channel because it facilitates separation of concerns), users can create a <code>MessageChannel</code> object on either thread and pass one of the <code>MessagePort</code>s on that <code>MessageChannel</code> to the other thread through a pre-existing channel, such as the global one.</p> <p>See <a href="#worker_threads_port_postmessage_value_transferlist"><code>port.postMessage()</code></a> for more information on how messages are passed, and what kind of JavaScript values can be successfully transported through the thread barrier.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'assert'</span>); <span class="hljs-keyword">const</span> { Worker, MessageChannel, MessagePort, isMainThread, parentPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>); <span class="hljs-keyword">if</span> (isMainThread) { <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> Worker(__filename); <span class="hljs-keyword">const</span> subChannel = <span class="hljs-keyword">new</span> MessageChannel(); worker.postMessage({ <span class="hljs-attr">hereIsYourPort</span>: subChannel.port1 }, [subChannel.port1]); subChannel.port2.on(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">value</span>) =></span> { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'received:'</span>, value); }); } <span class="hljs-keyword">else</span> { parentPort.once(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">value</span>) =></span> { assert(value.hereIsYourPort <span class="hljs-keyword">instanceof</span> MessagePort); value.hereIsYourPort.postMessage(<span class="hljs-string">'the worker is sending this'</span>); value.hereIsYourPort.close(); }); }</code></pre> <h3><code>new Worker(filename[, options])</code><span><a class="mark" href="#worker_threads_new_worker_filename_options" id="worker_threads_new_worker_filename_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v12.19.0</td> <td><p>The <code>trackUnmanagedFds</code> option was introduced.</p></td></tr> <tr><td>v12.17.0</td> <td><p>The <code>transferList</code> option was introduced.</p></td></tr> <tr><td>v12.17.0</td> <td><p>The <code>filename</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr> <tr><td>v12.16.0</td> <td><p>The <code>resourceLimits</code> option was introduced.</p></td></tr> <tr><td>v12.16.0</td> <td><p>The <code>argv</code> option was introduced.</p></td></tr> <tr><td>v10.5.0</td> <td><p><span>Added in: v10.5.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="url.html#url_the_whatwg_url_api" class="type"><URL></a> The path to the Worker’s main script or module. Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with <code>./</code> or <code>../</code>, or a WHATWG <code>URL</code> object using <code>file:</code> protocol. If <code>options.eval</code> is <code>true</code>, this is a string containing JavaScript code rather than a path.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <li><code>argv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any[]></a> List of arguments which would be stringified and appended to <code>process.argv</code> in the worker. This is mostly similar to the <code>workerData</code> but the values will be available on the global <code>process.argv</code> as if they were passed as CLI options to the script.</li> <li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> If set, specifies the initial value of <code>process.env</code> inside the Worker thread. As a special value, <a href="#worker_threads_worker_share_env"><code>worker.SHARE_ENV</code></a> may be used to specify that the parent thread and the child thread should share their environment variables; in that case, changes to one thread’s <code>process.env</code> object will affect the other thread as well. <strong>Default:</strong> <code>process.env</code>.</li> <li><code>eval</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code> and the first argument is a <code>string</code>, interpret the first argument to the constructor as a script that is executed once the worker is online.</li> <li><code>execArgv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> List of node CLI options passed to the worker. V8 options (such as <code>--max-old-space-size</code>) and options that affect the process (such as <code>--title</code>) are not supported. If set, this will be provided as <a href="process.html#process_process_execargv"><code>process.execArgv</code></a> inside the worker. By default, options will be inherited from the parent thread.</li> <li><code>stdin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If this is set to <code>true</code>, then <code>worker.stdin</code> will provide a writable stream whose contents will appear as <code>process.stdin</code> inside the Worker. By default, no data is provided.</li> <li><code>stdout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If this is set to <code>true</code>, then <code>worker.stdout</code> will not automatically be piped through to <code>process.stdout</code> in the parent.</li> <li><code>stderr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If this is set to <code>true</code>, then <code>worker.stderr</code> will not automatically be piped through to <code>process.stderr</code> in the parent.</li> <li><code>workerData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Any JavaScript value that will be cloned and made available as <a href="#worker_threads_worker_workerdata"><code>require('worker_threads').workerData</code></a>. The cloning will occur as described in the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>, and an error will be thrown if the object cannot be cloned (e.g. because it contains <code>function</code>s).</li> <li><code>trackUnmanagedFds</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If this is set to <code>true</code>, then the Worker will track raw file descriptors managed through <a href="fs.html#fs_fs_open_path_flags_mode_callback"><code>fs.open()</code></a> and <a href="fs.html#fs_fs_close_fd_callback"><code>fs.close()</code></a>, and close them when the Worker exits, similar to other resources like network sockets or file descriptors managed through the <a href="fs.html#fs_class_filehandle"><code>FileHandle</code></a> API. This option is automatically inherited by all nested <code>Worker</code>s. <strong>Default</strong>: <code>false</code>.</li> <li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a> If one or more <code>MessagePort</code>-like objects are passed in <code>workerData</code>, a <code>transferList</code> is required for those items or <a href="errors.html#errors_err_missing_message_port_in_transfer_list"><code>ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST</code></a> will be thrown. See <a href="#worker_threads_port_postmessage_value_transferlist"><code>port.postMessage()</code></a> for more information.</li> <li><code>resourceLimits</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An optional set of resource limits for the new JS engine instance. Reaching these limits will lead to termination of the <code>Worker</code> instance. These limits only affect the JS engine, and no external data, including no <code>ArrayBuffer</code>s. Even if these limits are set, the process may still abort if it encounters a global out-of-memory situation. <ul> <li><code>maxOldGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The maximum size of the main heap in MB.</li> <li><code>maxYoungGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The maximum size of a heap space for recently created objects.</li> <li><code>codeRangeSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The size of a pre-allocated memory range used for generated code.</li> <li><code>stackSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The default maximum stack size for the thread. Small values may lead to unusable Worker instances. <strong>Default:</strong> <code>4</code>.</li> </ul> </li> </ul> </li> </ul> <h3>Event: <code>'error'</code><span><a class="mark" href="#worker_threads_event_error" id="worker_threads_event_error">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>The <code>'error'</code> event is emitted if the worker thread throws an uncaught exception. In that case, the worker will be terminated.</p> <h3>Event: <code>'exit'</code><span><a class="mark" href="#worker_threads_event_exit" id="worker_threads_event_exit">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><code>exitCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>The <code>'exit'</code> event is emitted once the worker has stopped. If the worker exited by calling <a href="process.html#process_process_exit_code"><code>process.exit()</code></a>, the <code>exitCode</code> parameter will be the passed exit code. If the worker was terminated, the <code>exitCode</code> parameter will be <code>1</code>.</p> <p>This is the final event emitted by any <code>Worker</code> instance.</p> <h3>Event: <code>'message'</code><span><a class="mark" href="#worker_threads_event_message_1" id="worker_threads_event_message_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The transmitted value</li> </ul> <p>The <code>'message'</code> event is emitted when the worker thread has invoked <a href="#worker_threads_worker_postmessage_value_transferlist"><code>require('worker_threads').parentPort.postMessage()</code></a>. See the <a href="#worker_threads_event_message"><code>port.on('message')</code></a> event for more details.</p> <p>All messages sent from the worker thread will be emitted before the <a href="#worker_threads_event_exit"><code>'exit'</code> event</a> is emitted on the <code>Worker</code> object.</p> <h3>Event: <code>'messageerror'</code><span><a class="mark" href="#worker_threads_event_messageerror_1" id="worker_threads_event_messageerror_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v12.19.0</span> </div> <ul> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> An Error object</li> </ul> <p>The <code>'messageerror'</code> event is emitted when deserializing a message failed.</p> <h3>Event: <code>'online'</code><span><a class="mark" href="#worker_threads_event_online" id="worker_threads_event_online">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>The <code>'online'</code> event is emitted when the worker thread has started executing JavaScript code.</p> <h3><code>worker.getHeapSnapshot()</code><span><a class="mark" href="#worker_threads_worker_getheapsnapshot" id="worker_threads_worker_getheapsnapshot">#</a></span></h3> <div class="api_metadata"> <span>Added in: v12.17.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> A promise for a Readable Stream containing a V8 heap snapshot</li> </ul> <p>Returns a readable stream for a V8 snapshot of the current state of the Worker. See <a href="v8.html#v8_v8_getheapsnapshot"><code>v8.getHeapSnapshot()</code></a> for more details.</p> <p>If the Worker thread is no longer running, which may occur before the <a href="#worker_threads_event_exit"><code>'exit'</code> event</a> is emitted, the returned <code>Promise</code> will be rejected immediately with an <a href="errors.html#ERR_WORKER_NOT_RUNNING"><code>ERR_WORKER_NOT_RUNNING</code></a> error.</p> <h3><code>worker.performance</code><span><a class="mark" href="#worker_threads_worker_performance" id="worker_threads_worker_performance">#</a></span></h3> <div class="api_metadata"> <span>Added in: v12.22.0</span> </div> <p>An object that can be used to query performance information from a worker instance. Similar to <a href="#perf_hooks.md#perf_hooks_perf_hooks_performance"><code>perf_hooks.performance</code></a>.</p> <h4><code>performance.eventLoopUtilization([utilization1[, utilization2]])</code><span><a class="mark" href="#worker_threads_performance_eventlooputilization_utilization1_utilization2" id="worker_threads_performance_eventlooputilization_utilization1_utilization2">#</a></span></h4> <div class="api_metadata"> <span>Added in: v12.22.0</span> </div> <ul> <li><code>utilization1</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The result of a previous call to <code>eventLoopUtilization()</code>.</li> <li><code>utilization2</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The result of a previous call to <code>eventLoopUtilization()</code> prior to <code>utilization1</code>.</li> <li>Returns <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <li><code>idle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>active</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>utilization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> </li> </ul> <p>The same call as <a href="perf_hooks.md#perf_hooks_performance_eventlooputilization_utilization1_utilization2"><code>perf_hooks</code> <code>eventLoopUtilization()</code></a>, except the values of the worker instance are returned.</p> <p>One difference is that, unlike the main thread, bootstrapping within a worker is done within the event loop. So the event loop utilization will be immediately available once the worker's script begins execution.</p> <p>An <code>idle</code> time that does not increase does not indicate that the worker is stuck in bootstrap. The following examples shows how the worker's entire lifetime will never accumulate any <code>idle</code> time, but is still be able to process messages.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> { Worker, isMainThread, parentPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>); <span class="hljs-keyword">if</span> (isMainThread) { <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> Worker(__filename); <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> { worker.postMessage(<span class="hljs-string">'hi'</span>); <span class="hljs-built_in">console</span>.log(worker.performance.eventLoopUtilization()); }, <span class="hljs-number">100</span>).unref(); <span class="hljs-keyword">return</span>; } parentPort.on(<span class="hljs-string">'message'</span>, <span class="hljs-function">() =></span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'msg'</span>)).unref(); (<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">r</span>(<span class="hljs-params">n</span>) </span>{ <span class="hljs-keyword">if</span> (--n < <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span>; <span class="hljs-keyword">const</span> t = <span class="hljs-built_in">Date</span>.now(); <span class="hljs-keyword">while</span> (<span class="hljs-built_in">Date</span>.now() - t < <span class="hljs-number">300</span>); setImmediate(r, n); })(<span class="hljs-number">10</span>);</code></pre> <p>The event loop utilization of a worker is available only after the <a href="#worker_threads_event_online"><code>'online'</code> event</a> emitted, and if called before this, or after the <a href="#worker_threads_event_exit"><code>'exit'</code> event</a>, then all properties have the value of <code>0</code>.</p> <h3><code>worker.postMessage(value[, transferList])</code><span><a class="mark" href="#worker_threads_worker_postmessage_value_transferlist" id="worker_threads_worker_postmessage_value_transferlist">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li> </ul> <p>Send a message to the worker that will be received via <a href="#worker_threads_event_message"><code>require('worker_threads').parentPort.on('message')</code></a>. See <a href="#worker_threads_port_postmessage_value_transferlist"><code>port.postMessage()</code></a> for more details.</p> <h3><code>worker.ref()</code><span><a class="mark" href="#worker_threads_worker_ref" id="worker_threads_worker_ref">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>Opposite of <code>unref()</code>, calling <code>ref()</code> on a previously <code>unref()</code>ed worker will <em>not</em> let the program exit if it's the only active handle left (the default behavior). If the worker is <code>ref()</code>ed, calling <code>ref()</code> again will have no effect.</p> <h3><code>worker.resourceLimits</code><span><a class="mark" href="#worker_threads_worker_resourcelimits_1" id="worker_threads_worker_resourcelimits_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v12.16.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <li><code>maxYoungGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>maxOldGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>codeRangeSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>stackSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> </li> </ul> <p>Provides the set of JS engine resource constraints for this Worker thread. If the <code>resourceLimits</code> option was passed to the <a href="#worker_threads_class_worker"><code>Worker</code></a> constructor, this matches its values.</p> <p>If the worker has stopped, the return value is an empty object.</p> <h3><code>worker.stderr</code><span><a class="mark" href="#worker_threads_worker_stderr" id="worker_threads_worker_stderr">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><a href="stream.html#stream_class_stream_readable" class="type"><stream.Readable></a></li> </ul> <p>This is a readable stream which contains data written to <a href="process.html#process_process_stderr"><code>process.stderr</code></a> inside the worker thread. If <code>stderr: true</code> was not passed to the <a href="#worker_threads_class_worker"><code>Worker</code></a> constructor, then data will be piped to the parent thread's <a href="process.html#process_process_stderr"><code>process.stderr</code></a> stream.</p> <h3><code>worker.stdin</code><span><a class="mark" href="#worker_threads_worker_stdin" id="worker_threads_worker_stdin">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> | <a href="stream.html#stream_class_stream_writable" class="type"><stream.Writable></a></li> </ul> <p>If <code>stdin: true</code> was passed to the <a href="#worker_threads_class_worker"><code>Worker</code></a> constructor, this is a writable stream. The data written to this stream will be made available in the worker thread as <a href="process.html#process_process_stdin"><code>process.stdin</code></a>.</p> <h3><code>worker.stdout</code><span><a class="mark" href="#worker_threads_worker_stdout" id="worker_threads_worker_stdout">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><a href="stream.html#stream_class_stream_readable" class="type"><stream.Readable></a></li> </ul> <p>This is a readable stream which contains data written to <a href="process.html#process_process_stdout"><code>process.stdout</code></a> inside the worker thread. If <code>stdout: true</code> was not passed to the <a href="#worker_threads_class_worker"><code>Worker</code></a> constructor, then data will be piped to the parent thread's <a href="process.html#process_process_stdout"><code>process.stdout</code></a> stream.</p> <h3><code>worker.terminate()</code><span><a class="mark" href="#worker_threads_worker_terminate" id="worker_threads_worker_terminate">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v12.5.0</td> <td><p>This function now returns a Promise. Passing a callback is deprecated, and was useless up to this version, as the Worker was actually terminated synchronously. Terminating is now a fully asynchronous operation.</p></td></tr> <tr><td>v10.5.0</td> <td><p><span>Added in: v10.5.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Stop all JavaScript execution in the worker thread as soon as possible. Returns a Promise for the exit code that is fulfilled when the <a href="#worker_threads_event_exit"><code>'exit'</code> event</a> is emitted.</p> <h3><code>worker.threadId</code><span><a class="mark" href="#worker_threads_worker_threadid_1" id="worker_threads_worker_threadid_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>An integer identifier for the referenced thread. Inside the worker thread, it is available as <a href="#worker_threads_worker_threadid"><code>require('worker_threads').threadId</code></a>. This value is unique for each <code>Worker</code> instance inside a single process.</p> <h3><code>worker.unref()</code><span><a class="mark" href="#worker_threads_worker_unref" id="worker_threads_worker_unref">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>Calling <code>unref()</code> on a worker will allow the thread to exit if this is the only active handle in the event system. If the worker is already <code>unref()</code>ed calling <code>unref()</code> again will have no effect.</p> <!-- API END --> </div> </div> </div> </body> </html>