• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1<!DOCTYPE html>
2<html lang="en">
3<head>
4  <meta charset="utf-8">
5  <meta name="viewport" content="width=device-width">
6  <meta name="nodejs.org:node-version" content="v14.19.1">
7  <title>Worker threads | Node.js v14.19.1 Documentation</title>
8  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback">
9  <link rel="stylesheet" href="assets/style.css">
10  <link rel="stylesheet" href="assets/hljs.css">
11  <link rel="canonical" href="https://nodejs.org/api/worker_threads.html">
12</head>
13<body class="alt apidoc" id="api-section-worker_threads">
14  <div id="content" class="clearfix">
15    <div id="column2" class="interior">
16      <div id="intro" class="interior">
17        <a href="/" title="Go back to the home page">
18          Node.js
19        </a>
20      </div>
21      <ul>
22<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
23<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
24</ul>
25<hr class="line">
26<ul>
27<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
28<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
29<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
30<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
31<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
32<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
33<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
34<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
35<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
36<li><a href="console.html" class="nav-console">Console</a></li>
37<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
38<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
39<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
40<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
41<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
42<li><a href="dns.html" class="nav-dns">DNS</a></li>
43<li><a href="domain.html" class="nav-domain">Domain</a></li>
44<li><a href="errors.html" class="nav-errors">Errors</a></li>
45<li><a href="events.html" class="nav-events">Events</a></li>
46<li><a href="fs.html" class="nav-fs">File system</a></li>
47<li><a href="globals.html" class="nav-globals">Globals</a></li>
48<li><a href="http.html" class="nav-http">HTTP</a></li>
49<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
50<li><a href="https.html" class="nav-https">HTTPS</a></li>
51<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
52<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
53<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
54<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
55<li><a href="module.html" class="nav-module">Modules: <code>module</code> API</a></li>
56<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
57<li><a href="net.html" class="nav-net">Net</a></li>
58<li><a href="os.html" class="nav-os">OS</a></li>
59<li><a href="path.html" class="nav-path">Path</a></li>
60<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
61<li><a href="policy.html" class="nav-policy">Policies</a></li>
62<li><a href="process.html" class="nav-process">Process</a></li>
63<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
64<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
65<li><a href="readline.html" class="nav-readline">Readline</a></li>
66<li><a href="repl.html" class="nav-repl">REPL</a></li>
67<li><a href="report.html" class="nav-report">Report</a></li>
68<li><a href="stream.html" class="nav-stream">Stream</a></li>
69<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
70<li><a href="timers.html" class="nav-timers">Timers</a></li>
71<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
72<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
73<li><a href="tty.html" class="nav-tty">TTY</a></li>
74<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
75<li><a href="url.html" class="nav-url">URL</a></li>
76<li><a href="util.html" class="nav-util">Utilities</a></li>
77<li><a href="v8.html" class="nav-v8">V8</a></li>
78<li><a href="vm.html" class="nav-vm">VM</a></li>
79<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
80<li><a href="worker_threads.html" class="nav-worker_threads active">Worker threads</a></li>
81<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
82</ul>
83<hr class="line">
84<ul>
85<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
86</ul>
87    </div>
88
89    <div id="column1" data-id="worker_threads" class="interior">
90      <header>
91        <div class="header-container">
92          <h1>Node.js v14.19.1 documentation</h1>
93          <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden>
94            <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24">
95              <path fill="none" d="M0 0h24v24H0z" />
96              <path d="M11.1 12.08c-2.33-4.51-.5-8.48.53-10.07C6.27 2.2 1.98 6.59 1.98 12c0 .14.02.28.02.42.62-.27 1.29-.42 2-.42 1.66 0 3.18.83 4.1 2.15A4.01 4.01 0 0111 18c0 1.52-.87 2.83-2.12 3.51.98.32 2.03.5 3.11.5 3.5 0 6.58-1.8 8.37-4.52-2.36.23-6.98-.97-9.26-5.41z"/>
97              <path d="M7 16h-.18C6.4 14.84 5.3 14 4 14c-1.66 0-3 1.34-3 3s1.34 3 3 3h3c1.1 0 2-.9 2-2s-.9-2-2-2z"/>
98            </svg>
99            <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24">
100              <path d="M0 0h24v24H0z" fill="none" />
101              <path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/>
102            </svg>
103          </button>
104        </div>
105        <div id="gtoc">
106          <ul>
107            <li>
108              <a href="index.html">Index</a>
109            </li>
110            <li>
111              <a href="all.html">View on single page</a>
112            </li>
113            <li>
114              <a href="worker_threads.json">View as JSON</a>
115            </li>
116
117    <li class="version-picker">
118      <a href="#">View another version <span>&#x25bc;</span></a>
119      <ol class="version-picker"><li><a href="https://nodejs.org/docs/latest-v17.x/api/worker_threads.html">17.x</a></li>
120<li><a href="https://nodejs.org/docs/latest-v16.x/api/worker_threads.html">16.x <b>LTS</b></a></li>
121<li><a href="https://nodejs.org/docs/latest-v15.x/api/worker_threads.html">15.x</a></li>
122<li><a href="https://nodejs.org/docs/latest-v14.x/api/worker_threads.html">14.x <b>LTS</b></a></li>
123<li><a href="https://nodejs.org/docs/latest-v13.x/api/worker_threads.html">13.x</a></li>
124<li><a href="https://nodejs.org/docs/latest-v12.x/api/worker_threads.html">12.x <b>LTS</b></a></li>
125<li><a href="https://nodejs.org/docs/latest-v11.x/api/worker_threads.html">11.x</a></li>
126<li><a href="https://nodejs.org/docs/latest-v10.x/api/worker_threads.html">10.x</a></li></ol>
127    </li>
128
129            <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/master/doc/api/worker_threads.md">Edit on GitHub</a></li>
130          </ul>
131        </div>
132        <hr>
133      </header>
134
135      <details id="toc" open><summary>Table of contents</summary><ul>
136<li><span class="stability_2"><a href="#worker_threads_worker_threads">Worker threads</a></span>
137<ul>
138<li><span class="stability_1"><a href="#worker_threads_worker_getenvironmentdata_key"><code>worker.getEnvironmentData(key)</code></a></span></li>
139<li><a href="#worker_threads_worker_ismainthread"><code>worker.isMainThread</code></a></li>
140<li><a href="#worker_threads_worker_markasuntransferable_object"><code>worker.markAsUntransferable(object)</code></a></li>
141<li><a href="#worker_threads_worker_movemessageporttocontext_port_contextifiedsandbox"><code>worker.moveMessagePortToContext(port, contextifiedSandbox)</code></a></li>
142<li><a href="#worker_threads_worker_parentport"><code>worker.parentPort</code></a></li>
143<li><a href="#worker_threads_worker_receivemessageonport_port"><code>worker.receiveMessageOnPort(port)</code></a></li>
144<li><a href="#worker_threads_worker_resourcelimits"><code>worker.resourceLimits</code></a></li>
145<li><a href="#worker_threads_worker_share_env"><code>worker.SHARE_ENV</code></a></li>
146<li><span class="stability_1"><a href="#worker_threads_worker_setenvironmentdata_key_value"><code>worker.setEnvironmentData(key[, value])</code></a></span></li>
147<li><a href="#worker_threads_worker_threadid"><code>worker.threadId</code></a></li>
148<li><a href="#worker_threads_worker_workerdata"><code>worker.workerData</code></a></li>
149<li><a href="#worker_threads_class_messagechannel">Class: <code>MessageChannel</code></a></li>
150<li><a href="#worker_threads_class_messageport">Class: <code>MessagePort</code></a>
151<ul>
152<li><a href="#worker_threads_event_close">Event: <code>'close'</code></a></li>
153<li><a href="#worker_threads_event_message">Event: <code>'message'</code></a></li>
154<li><a href="#worker_threads_event_messageerror">Event: <code>'messageerror'</code></a></li>
155<li><a href="#worker_threads_port_close"><code>port.close()</code></a></li>
156<li><a href="#worker_threads_port_postmessage_value_transferlist"><code>port.postMessage(value[, transferList])</code></a>
157<ul>
158<li><a href="#worker_threads_considerations_when_transferring_typedarrays_and_buffers">Considerations when transferring TypedArrays and Buffers</a></li>
159</ul>
160</li>
161<li><a href="#worker_threads_port_ref"><code>port.ref()</code></a></li>
162<li><a href="#worker_threads_port_start"><code>port.start()</code></a></li>
163<li><a href="#worker_threads_port_unref"><code>port.unref()</code></a></li>
164</ul>
165</li>
166<li><a href="#worker_threads_class_worker">Class: <code>Worker</code></a>
167<ul>
168<li><a href="#worker_threads_new_worker_filename_options"><code>new Worker(filename[, options])</code></a></li>
169<li><a href="#worker_threads_event_error">Event: <code>'error'</code></a></li>
170<li><a href="#worker_threads_event_exit">Event: <code>'exit'</code></a></li>
171<li><a href="#worker_threads_event_message_1">Event: <code>'message'</code></a></li>
172<li><a href="#worker_threads_event_messageerror_1">Event: <code>'messageerror'</code></a></li>
173<li><a href="#worker_threads_event_online">Event: <code>'online'</code></a></li>
174<li><a href="#worker_threads_worker_getheapsnapshot"><code>worker.getHeapSnapshot()</code></a></li>
175<li><a href="#worker_threads_worker_performance"><code>worker.performance</code></a>
176<ul>
177<li><a href="#worker_threads_performance_eventlooputilization_utilization1_utilization2"><code>performance.eventLoopUtilization([utilization1[, utilization2]])</code></a></li>
178</ul>
179</li>
180<li><a href="#worker_threads_worker_postmessage_value_transferlist"><code>worker.postMessage(value[, transferList])</code></a></li>
181<li><a href="#worker_threads_worker_ref"><code>worker.ref()</code></a></li>
182<li><a href="#worker_threads_worker_resourcelimits_1"><code>worker.resourceLimits</code></a></li>
183<li><a href="#worker_threads_worker_stderr"><code>worker.stderr</code></a></li>
184<li><a href="#worker_threads_worker_stdin"><code>worker.stdin</code></a></li>
185<li><a href="#worker_threads_worker_stdout"><code>worker.stdout</code></a></li>
186<li><a href="#worker_threads_worker_terminate"><code>worker.terminate()</code></a></li>
187<li><a href="#worker_threads_worker_threadid_1"><code>worker.threadId</code></a></li>
188<li><a href="#worker_threads_worker_unref"><code>worker.unref()</code></a></li>
189</ul>
190</li>
191<li><a href="#worker_threads_notes">Notes</a>
192<ul>
193<li><a href="#worker_threads_synchronous_blocking_of_stdio">Synchronous blocking of stdio</a></li>
194<li><a href="#worker_threads_launching_worker_threads_from_preload_scripts">Launching worker threads from preload scripts</a></li>
195</ul>
196</li>
197</ul>
198</li>
199</ul></details>
200
201      <div id="apicontent">
202        <h2>Worker threads<span><a class="mark" href="#worker_threads_worker_threads" id="worker_threads_worker_threads">#</a></span></h2>
203
204<p></p><div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
205<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v14.19.1/lib/worker_threads.js">lib/worker_threads.js</a></p>
206<p>The <code>worker_threads</code> module enables the use of threads that execute JavaScript
207in parallel. To access it:</p>
208<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>
209<p>Workers (threads) are useful for performing CPU-intensive JavaScript operations.
210They will not help much with I/O-intensive work. Node.js’s built-in asynchronous
211I/O operations are more efficient than Workers can be.</p>
212<p>Unlike <code>child_process</code> or <code>cluster</code>, <code>worker_threads</code> can share memory. They do
213so by transferring <code>ArrayBuffer</code> instances or sharing <code>SharedArrayBuffer</code>
214instances.</p>
215<pre><code class="language-js"><span class="hljs-keyword">const</span> {
216  <span class="hljs-title class_">Worker</span>, isMainThread, parentPort, workerData
217} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);
218
219<span class="hljs-keyword">if</span> (isMainThread) {
220  <span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-keyword">function</span> <span class="hljs-title function_">parseJSAsync</span>(<span class="hljs-params">script</span>) {
221    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
222      <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename, {
223        <span class="hljs-attr">workerData</span>: script
224      });
225      worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, resolve);
226      worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, reject);
227      worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
228        <span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</span>)
229          <span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">`Worker stopped with exit code <span class="hljs-subst">${code}</span>`</span>));
230      });
231    });
232  };
233} <span class="hljs-keyword">else</span> {
234  <span class="hljs-keyword">const</span> { parse } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'some-js-parsing-library'</span>);
235  <span class="hljs-keyword">const</span> script = workerData;
236  parentPort.<span class="hljs-title function_">postMessage</span>(<span class="hljs-title function_">parse</span>(script));
237}</code></pre>
238<p>The above example spawns a Worker thread for each <code>parse()</code> call. In actual
239practice, use a pool of Workers instead for these kinds of tasks. Otherwise, the
240overhead of creating Workers would likely exceed their benefit.</p>
241<p>When implementing a worker pool, use the <a href="async_hooks.html#async_hooks_class_asyncresource"><code>AsyncResource</code></a> API to inform
242diagnostic tools (e.g. in order to provide asynchronous stack traces) about the
243correlation between tasks and their outcomes. See
244<a href="async_hooks.html#async-resource-worker-pool">"Using <code>AsyncResource</code> for a <code>Worker</code> thread pool"</a>
245in the <code>async_hooks</code> documentation for an example implementation.</p>
246<p>Worker threads inherit non-process-specific options by default. Refer to
247<a href="#worker_threads_new_worker_filename_options"><code>Worker constructor options</code></a> to know how to customize worker thread options,
248specifically <code>argv</code> and <code>execArgv</code> options.</p>
249<section><h3><code>worker.getEnvironmentData(key)</code><span><a class="mark" href="#worker_threads_worker_getenvironmentdata_key" id="worker_threads_worker_getenvironmentdata_key">#</a></span></h3>
250<div class="api_metadata">
251<span>Added in: v14.18.0</span>
252</div>
253<p></p><div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
254<ul>
255<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Any arbitrary, cloneable JavaScript value that can be used as a
256<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map" class="type">&#x3C;Map></a> key.</li>
257<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
258</ul>
259<p>Within a worker thread, <code>worker.getEnvironmentData()</code> returns a clone
260of data passed to the spawning thread's <code>worker.setEnvironmentData()</code>.
261Every new <code>Worker</code> receives its own copy of the environment data
262automatically.</p>
263<pre><code class="language-js"><span class="hljs-keyword">const</span> {
264  <span class="hljs-title class_">Worker</span>,
265  isMainThread,
266  setEnvironmentData,
267  getEnvironmentData,
268} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);
269
270<span class="hljs-keyword">if</span> (isMainThread) {
271  <span class="hljs-title function_">setEnvironmentData</span>(<span class="hljs-string">'Hello'</span>, <span class="hljs-string">'World!'</span>);
272  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
273} <span class="hljs-keyword">else</span> {
274  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getEnvironmentData</span>(<span class="hljs-string">'Hello'</span>));  <span class="hljs-comment">// Prints 'World!'.</span>
275}</code></pre>
276</section><section><h3><code>worker.isMainThread</code><span><a class="mark" href="#worker_threads_worker_ismainthread" id="worker_threads_worker_ismainthread">#</a></span></h3>
277<div class="api_metadata">
278<span>Added in: v10.5.0</span>
279</div>
280<ul>
281<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
282</ul>
283<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>
284<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, isMainThread } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);
285
286<span class="hljs-keyword">if</span> (isMainThread) {
287  <span class="hljs-comment">// This re-loads the current file inside a Worker instance.</span>
288  <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
289} <span class="hljs-keyword">else</span> {
290  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Inside Worker!'</span>);
291  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(isMainThread);  <span class="hljs-comment">// Prints 'false'.</span>
292}</code></pre>
293</section><section><h3><code>worker.markAsUntransferable(object)</code><span><a class="mark" href="#worker_threads_worker_markasuntransferable_object" id="worker_threads_worker_markasuntransferable_object">#</a></span></h3>
294<div class="api_metadata">
295<span>Added in: v14.5.0</span>
296</div>
297<p>Mark an object as not transferable. If <code>object</code> occurs in the transfer list of
298a <a href="#worker_threads_port_postmessage_value_transferlist"><code>port.postMessage()</code></a> call, it will be ignored.</p>
299<p>In particular, this makes sense for objects that can be cloned, rather than
300transferred, and which are used by other objects on the sending side.
301For example, Node.js marks the <code>ArrayBuffer</code>s it uses for its
302<a href="buffer.html#buffer_static_method_buffer_allocunsafe_size"><code>Buffer</code> pool</a> with this.</p>
303<p>This operation cannot be undone.</p>
304<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span>, markAsUntransferable } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);
305
306<span class="hljs-keyword">const</span> pooledBuffer = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">8</span>);
307<span class="hljs-keyword">const</span> typedArray1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint</span>8<span class="hljs-built_in">Array</span>(pooledBuffer);
308<span class="hljs-keyword">const</span> typedArray2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Float</span>64<span class="hljs-built_in">Array</span>(pooledBuffer);
309
310<span class="hljs-title function_">markAsUntransferable</span>(pooledBuffer);
311
312<span class="hljs-keyword">const</span> { port1 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
313port1.<span class="hljs-title function_">postMessage</span>(typedArray1, [ typedArray1.<span class="hljs-property">buffer</span> ]);
314
315<span class="hljs-comment">// The following line prints the contents of typedArray1 -- it still owns</span>
316<span class="hljs-comment">// its memory and has been cloned, not transferred. Without</span>
317<span class="hljs-comment">// `markAsUntransferable()`, this would print an empty Uint8Array.</span>
318<span class="hljs-comment">// typedArray2 is intact as well.</span>
319<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(typedArray1);
320<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(typedArray2);</code></pre>
321<p>There is no equivalent to this API in browsers.</p>
322</section><section><h3><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></h3>
323<div class="api_metadata">
324<span>Added in: v11.13.0</span>
325</div>
326<ul>
327<li>
328<p><code>port</code> <a href="worker_threads.html#worker_threads_class_messageport" class="type">&#x3C;MessagePort></a> The message port which will be transferred.</p>
329</li>
330<li>
331<p><code>contextifiedSandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> A <a href="vm.html#vm_what_does_it_mean_to_contextify_an_object">contextified</a> object as returned by the
332<code>vm.createContext()</code> method.</p>
333</li>
334<li>
335<p>Returns: <a href="worker_threads.html#worker_threads_class_messageport" class="type">&#x3C;MessagePort></a></p>
336</li>
337</ul>
338<p>Transfer a <code>MessagePort</code> to a different <a href="vm.html"><code>vm</code></a> Context. The original <code>port</code>
339object will be rendered unusable, and the returned <code>MessagePort</code> instance will
340take its place.</p>
341<p>The returned <code>MessagePort</code> will be an object in the target context, and will
342inherit from its global <code>Object</code> class. Objects passed to the
343<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
344and inherit from its global <code>Object</code> class.</p>
345<p>However, the created <code>MessagePort</code> will no longer inherit from
346<a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget"><code>EventTarget</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
347events using it.</p>
348</section><section><h3><code>worker.parentPort</code><span><a class="mark" href="#worker_threads_worker_parentport" id="worker_threads_worker_parentport">#</a></span></h3>
349<div class="api_metadata">
350<span>Added in: v10.5.0</span>
351</div>
352<ul>
353<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> | <a href="worker_threads.html#worker_threads_class_messageport" class="type">&#x3C;MessagePort></a></li>
354</ul>
355<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>
356allowing communication with the parent thread. Messages sent using
357<code>parentPort.postMessage()</code> will be available in the parent thread
358using <code>worker.on('message')</code>, and messages sent from the parent thread
359using <code>worker.postMessage()</code> will be available in this thread using
360<code>parentPort.on('message')</code>.</p>
361<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, isMainThread, parentPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);
362
363<span class="hljs-keyword">if</span> (isMainThread) {
364  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
365  worker.<span class="hljs-title function_">once</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> {
366    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message);  <span class="hljs-comment">// Prints 'Hello, world!'.</span>
367  });
368  worker.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'Hello, world!'</span>);
369} <span class="hljs-keyword">else</span> {
370  <span class="hljs-comment">// When a message from the parent thread is received, send it back:</span>
371  parentPort.<span class="hljs-title function_">once</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> {
372    parentPort.<span class="hljs-title function_">postMessage</span>(message);
373  });
374}</code></pre>
375</section><section><h3><code>worker.receiveMessageOnPort(port)</code><span><a class="mark" href="#worker_threads_worker_receivemessageonport_port" id="worker_threads_worker_receivemessageonport_port">#</a></span></h3>
376<div class="api_metadata">
377<span>Added in: v12.3.0</span>
378</div>
379<ul>
380<li>
381<p><code>port</code> <a href="worker_threads.html#worker_threads_class_messageport" class="type">&#x3C;MessagePort></a></p>
382</li>
383<li>
384<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></p>
385</li>
386</ul>
387<p>Receive a single message from a given <code>MessagePort</code>. If no message is available,
388<code>undefined</code> is returned, otherwise an object with a single <code>message</code> property
389that contains the message payload, corresponding to the oldest message in the
390<code>MessagePort</code>’s queue.</p>
391<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span>, receiveMessageOnPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);
392<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
393port1.<span class="hljs-title function_">postMessage</span>({ <span class="hljs-attr">hello</span>: <span class="hljs-string">'world'</span> });
394
395<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">receiveMessageOnPort</span>(port2));
396<span class="hljs-comment">// Prints: { message: { hello: 'world' } }</span>
397<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">receiveMessageOnPort</span>(port2));
398<span class="hljs-comment">// Prints: undefined</span></code></pre>
399<p>When this function is used, no <code>'message'</code> event will be emitted and the
400<code>onmessage</code> listener will not be invoked.</p>
401</section><section><h3><code>worker.resourceLimits</code><span><a class="mark" href="#worker_threads_worker_resourcelimits" id="worker_threads_worker_resourcelimits">#</a></span></h3>
402<div class="api_metadata">
403<span>Added in: v13.2.0, v12.16.0</span>
404</div>
405<ul>
406<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
407<ul>
408<li><code>maxYoungGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
409<li><code>maxOldGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
410<li><code>codeRangeSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
411<li><code>stackSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
412</ul>
413</li>
414</ul>
415<p>Provides the set of JS engine resource constraints inside this Worker thread.
416If the <code>resourceLimits</code> option was passed to the <a href="#worker_threads_class_worker"><code>Worker</code></a> constructor,
417this matches its values.</p>
418<p>If this is used in the main thread, its value is an empty object.</p>
419</section><section><h3><code>worker.SHARE_ENV</code><span><a class="mark" href="#worker_threads_worker_share_env" id="worker_threads_worker_share_env">#</a></span></h3>
420<div class="api_metadata">
421<span>Added in: v11.14.0</span>
422</div>
423<ul>
424<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a></li>
425</ul>
426<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>
427constructor, to indicate that the current thread and the Worker thread should
428share read and write access to the same set of environment variables.</p>
429<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, <span class="hljs-variable constant_">SHARE_ENV</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);
430<span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(<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>: <span class="hljs-variable constant_">SHARE_ENV</span> })
431  .<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">() =></span> {
432    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(process.<span class="hljs-property">env</span>.<span class="hljs-property">SET_IN_WORKER</span>);  <span class="hljs-comment">// Prints 'foo'.</span>
433  });</code></pre>
434</section><section><h3><code>worker.setEnvironmentData(key[, value])</code><span><a class="mark" href="#worker_threads_worker_setenvironmentdata_key_value" id="worker_threads_worker_setenvironmentdata_key_value">#</a></span></h3>
435<div class="api_metadata">
436<span>Added in: v14.18.0</span>
437</div>
438<p></p><div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
439<ul>
440<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Any arbitrary, cloneable JavaScript value that can be used as a
441<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map" class="type">&#x3C;Map></a> key.</li>
442<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Any arbitrary, cloneable JavaScript value that will be cloned
443and passed automatically to all new <code>Worker</code> instances. If <code>value</code> is passed
444as <code>undefined</code>, any previously set value for the <code>key</code> will be deleted.</li>
445</ul>
446<p>The <code>worker.setEnvironmentData()</code> API sets the content of
447<code>worker.getEnvironmentData()</code> in the current thread and all new <code>Worker</code>
448instances spawned from the current context.</p>
449</section><section><h3><code>worker.threadId</code><span><a class="mark" href="#worker_threads_worker_threadid" id="worker_threads_worker_threadid">#</a></span></h3>
450<div class="api_metadata">
451<span>Added in: v10.5.0</span>
452</div>
453<ul>
454<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
455</ul>
456<p>An integer identifier for the current thread. On the corresponding worker object
457(if there is any), it is available as <a href="#worker_threads_worker_threadid_1"><code>worker.threadId</code></a>.
458This value is unique for each <a href="#worker_threads_class_worker"><code>Worker</code></a> instance inside a single process.</p>
459</section><section><h3><code>worker.workerData</code><span><a class="mark" href="#worker_threads_worker_workerdata" id="worker_threads_worker_workerdata">#</a></span></h3>
460<div class="api_metadata">
461<span>Added in: v10.5.0</span>
462</div>
463<p>An arbitrary JavaScript value that contains a clone of the data passed
464to this thread’s <code>Worker</code> constructor.</p>
465<p>The data is cloned as if using <a href="#worker_threads_port_postmessage_value_transferlist"><code>postMessage()</code></a>,
466according 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>
467<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, isMainThread, workerData } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);
468
469<span class="hljs-keyword">if</span> (isMainThread) {
470  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename, { <span class="hljs-attr">workerData</span>: <span class="hljs-string">'Hello, world!'</span> });
471} <span class="hljs-keyword">else</span> {
472  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(workerData);  <span class="hljs-comment">// Prints 'Hello, world!'.</span>
473}</code></pre>
474</section><section><h3>Class: <code>MessageChannel</code><span><a class="mark" href="#worker_threads_class_messagechannel" id="worker_threads_class_messagechannel">#</a></span></h3>
475<div class="api_metadata">
476<span>Added in: v10.5.0</span>
477</div>
478<p>Instances of the <code>worker.MessageChannel</code> class represent an asynchronous,
479two-way communications channel.
480The <code>MessageChannel</code> has no methods of its own. <code>new MessageChannel()</code>
481yields an object with <code>port1</code> and <code>port2</code> properties, which refer to linked
482<a href="#worker_threads_class_messageport"><code>MessagePort</code></a> instances.</p>
483<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);
484
485<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
486port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'received'</span>, message));
487port2.<span class="hljs-title function_">postMessage</span>({ <span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span> });
488<span class="hljs-comment">// Prints: received { foo: 'bar' } from the `port1.on('message')` listener</span></code></pre>
489</section><section><h3>Class: <code>MessagePort</code><span><a class="mark" href="#worker_threads_class_messageport" id="worker_threads_class_messageport">#</a></span></h3>
490<div class="api_metadata">
491<details class="changelog"><summary>History</summary>
492<table>
493<tbody><tr><th>Version</th><th>Changes</th></tr>
494<tr><td>v14.7.0</td>
495<td><p>This class now inherits from <code>EventTarget</code> rather than from <code>EventEmitter</code>.</p></td></tr>
496<tr><td>v10.5.0</td>
497<td><p><span>Added in: v10.5.0</span></p></td></tr>
498</tbody></table>
499</details>
500</div>
501<ul>
502<li>Extends: <a href="events.html#events_class_eventtarget" class="type">&#x3C;EventTarget></a></li>
503</ul>
504<p>Instances of the <code>worker.MessagePort</code> class represent one end of an
505asynchronous, two-way communications channel. It can be used to transfer
506structured data, memory regions and other <code>MessagePort</code>s between different
507<a href="#worker_threads_class_worker"><code>Worker</code></a>s.</p>
508<p>This implementation matches <a href="https://developer.mozilla.org/en-US/docs/Web/API/MessagePort">browser <code>MessagePort</code></a>s.</p>
509<h4>Event: <code>'close'</code><span><a class="mark" href="#worker_threads_event_close" id="worker_threads_event_close">#</a></span></h4>
510<div class="api_metadata">
511<span>Added in: v10.5.0</span>
512</div>
513<p>The <code>'close'</code> event is emitted once either side of the channel has been
514disconnected.</p>
515<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);
516<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
517
518<span class="hljs-comment">// Prints:</span>
519<span class="hljs-comment">//   foobar</span>
520<span class="hljs-comment">//   closed!</span>
521port2.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message));
522port2.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'closed!'</span>));
523
524port1.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'foobar'</span>);
525port1.<span class="hljs-title function_">close</span>();</code></pre>
526<h4>Event: <code>'message'</code><span><a class="mark" href="#worker_threads_event_message" id="worker_threads_event_message">#</a></span></h4>
527<div class="api_metadata">
528<span>Added in: v10.5.0</span>
529</div>
530<ul>
531<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The transmitted value</li>
532</ul>
533<p>The <code>'message'</code> event is emitted for any incoming message, containing the cloned
534input of <a href="#worker_threads_port_postmessage_value_transferlist"><code>port.postMessage()</code></a>.</p>
535<p>Listeners on this event will receive a clone of the <code>value</code> parameter as passed
536to <code>postMessage()</code> and no further arguments.</p>
537<h4>Event: <code>'messageerror'</code><span><a class="mark" href="#worker_threads_event_messageerror" id="worker_threads_event_messageerror">#</a></span></h4>
538<div class="api_metadata">
539<span>Added in: v14.5.0</span>
540</div>
541<ul>
542<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> An Error object</li>
543</ul>
544<p>The <code>'messageerror'</code> event is emitted when deserializing a message failed.</p>
545<p>Currently, this event is emitted when there is an error occurring while
546instantiating the posted JS object on the receiving end. Such situations
547are rare, but can happen, for instance, when certain Node.js API objects
548are received in a <code>vm.Context</code> (where Node.js APIs are currently
549unavailable).</p>
550<h4><code>port.close()</code><span><a class="mark" href="#worker_threads_port_close" id="worker_threads_port_close">#</a></span></h4>
551<div class="api_metadata">
552<span>Added in: v10.5.0</span>
553</div>
554<p>Disables further sending of messages on either side of the connection.
555This method can be called when no further communication will happen over this
556<code>MessagePort</code>.</p>
557<p>The <a href="#worker_threads_event_close"><code>'close'</code> event</a> will be emitted on both <code>MessagePort</code> instances that
558are part of the channel.</p>
559<h4><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></h4>
560<div class="api_metadata">
561<details class="changelog"><summary>History</summary>
562<table>
563<tbody><tr><th>Version</th><th>Changes</th></tr>
564<tr><td>v14.18.0</td>
565<td><p>Add 'BlockList' to the list of cloneable types.</p></td></tr>
566<tr><td>v14.18.0</td>
567<td><p>Add 'Histogram' types to the list of cloneable types.</p></td></tr>
568<tr><td>v14.5.0</td>
569<td><p>Added <code>KeyObject</code> to the list of cloneable types.</p></td></tr>
570<tr><td>v14.5.0</td>
571<td><p>Added <code>FileHandle</code> to the list of transferable types.</p></td></tr>
572<tr><td>v10.5.0</td>
573<td><p><span>Added in: v10.5.0</span></p></td></tr>
574</tbody></table>
575</details>
576</div>
577<ul>
578<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
579<li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a></li>
580</ul>
581<p>Sends a JavaScript value to the receiving side of this channel.
582<code>value</code> will be transferred in a way which is compatible with
583the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>.</p>
584<p>In particular, the significant differences to <code>JSON</code> are:</p>
585<ul>
586<li><code>value</code> may contain circular references.</li>
587<li><code>value</code> may contain instances of builtin JS types such as <code>RegExp</code>s,
588<code>BigInt</code>s, <code>Map</code>s, <code>Set</code>s, etc.</li>
589<li><code>value</code> may contain typed arrays, both using <code>ArrayBuffer</code>s
590and <code>SharedArrayBuffer</code>s.</li>
591<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>
592<li><code>value</code> may not contain native (C++-backed) objects other than:
593<ul>
594<li><a href="fs.html#fs_class_filehandle" class="type">&#x3C;FileHandle></a>s,</li>
595<li><a href="perf_hooks.html#perf_hooks_class_histogram" class="type">&#x3C;Histogram></a>s,</li>
596<li><a href="crypto.html#crypto_class_keyobject" class="type">&#x3C;KeyObject></a>s,</li>
597<li><a href="worker_threads.html#worker_threads_class_messageport" class="type">&#x3C;MessagePort></a>s,</li>
598<li><a href="net.html#net_class_net_blocklist" class="type">&#x3C;net.BlockList></a>s,</li>
599<li><a href="net.html#net_class_net_socketaddress" class="type">&#x3C;net.SocketAddress></a>es,</li>
600</ul>
601</li>
602</ul>
603<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);
604<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
605
606port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message));
607
608<span class="hljs-keyword">const</span> circularData = {};
609circularData.<span class="hljs-property">foo</span> = circularData;
610<span class="hljs-comment">// Prints: { foo: [Circular] }</span>
611port2.<span class="hljs-title function_">postMessage</span>(circularData);</code></pre>
612<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
613<a href="fs.html#fs_class_filehandle"><code>FileHandle</code></a> objects.
614After transferring, they will not be usable on the sending side of the channel
615anymore (even if they are not contained in <code>value</code>). Unlike with
616<a href="child_process.html">child processes</a>, transferring handles such as network sockets is currently
617not supported.</p>
618<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
619from either thread. They cannot be listed in <code>transferList</code>.</p>
620<p><code>value</code> may still contain <code>ArrayBuffer</code> instances that are not in
621<code>transferList</code>; in that case, the underlying memory is copied rather than moved.</p>
622<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);
623<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
624
625port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message));
626
627<span class="hljs-keyword">const</span> uint8Array = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint</span>8<span class="hljs-built_in">Array</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> ]);
628<span class="hljs-comment">// This posts a copy of `uint8Array`:</span>
629port2.<span class="hljs-title function_">postMessage</span>(uint8Array);
630<span class="hljs-comment">// This does not copy data, but renders `uint8Array` unusable:</span>
631port2.<span class="hljs-title function_">postMessage</span>(uint8Array, [ uint8Array.<span class="hljs-property">buffer</span> ]);
632
633<span class="hljs-comment">// The memory for the `sharedUint8Array` will be accessible from both the</span>
634<span class="hljs-comment">// original and the copy received by `.on('message')`:</span>
635<span class="hljs-keyword">const</span> sharedUint8Array = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint</span>8<span class="hljs-built_in">Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">SharedArrayBuffer</span>(<span class="hljs-number">4</span>));
636port2.<span class="hljs-title function_">postMessage</span>(sharedUint8Array);
637
638<span class="hljs-comment">// This transfers a freshly created message port to the receiver.</span>
639<span class="hljs-comment">// This can be used, for example, to create communication channels between</span>
640<span class="hljs-comment">// multiple `Worker` threads that are children of the same parent thread.</span>
641<span class="hljs-keyword">const</span> otherChannel = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
642port2.<span class="hljs-title function_">postMessage</span>({ <span class="hljs-attr">port</span>: otherChannel.<span class="hljs-property">port1</span> }, [ otherChannel.<span class="hljs-property">port1</span> ]);</code></pre>
643<p>Because the object cloning uses the structured clone algorithm,
644non-enumerable properties, property accessors, and object prototypes are
645not preserved. In particular, <a href="buffer.html"><code>Buffer</code></a> objects will be read as
646plain <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>
647<p>The message object will be cloned immediately, and can be modified after
648posting without having side effects.</p>
649<p>For more information on the serialization and deserialization mechanisms
650behind this API, see the <a href="v8.html#v8_serialization_api">serialization API of the <code>v8</code> module</a>.</p>
651<h5>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></h5>
652<p>All <code>TypedArray</code> and <code>Buffer</code> instances are views over an underlying
653<code>ArrayBuffer</code>. That is, it is the <code>ArrayBuffer</code> that actually stores
654the raw data while the <code>TypedArray</code> and <code>Buffer</code> objects provide a
655way of viewing and manipulating the data. It is possible and common
656for multiple views to be created over the same <code>ArrayBuffer</code> instance.
657Great care must be taken when using a transfer list to transfer an
658<code>ArrayBuffer</code> as doing so will cause all <code>TypedArray</code> and <code>Buffer</code>
659instances that share that same <code>ArrayBuffer</code> to become unusable.</p>
660<pre><code class="language-js"><span class="hljs-keyword">const</span> ab = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>);
661
662<span class="hljs-keyword">const</span> u1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint</span>8<span class="hljs-built_in">Array</span>(ab);
663<span class="hljs-keyword">const</span> u2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint</span>16<span class="hljs-built_in">Array</span>(ab);
664
665<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(u2.<span class="hljs-property">length</span>);  <span class="hljs-comment">// prints 5</span>
666
667port.<span class="hljs-title function_">postMessage</span>(u1, [u1.<span class="hljs-property">buffer</span>]);
668
669<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(u2.<span class="hljs-property">length</span>);  <span class="hljs-comment">// prints 0</span></code></pre>
670<p>For <code>Buffer</code> instances, specifically, whether the underlying
671<code>ArrayBuffer</code> can be transferred or cloned depends entirely on how
672instances were created, which often cannot be reliably determined.</p>
673<p>An <code>ArrayBuffer</code> can be marked with <a href="#worker_threads_worker_markasuntransferable_object"><code>markAsUntransferable()</code></a> to indicate
674that it should always be cloned and never transferred.</p>
675<p>Depending on how a <code>Buffer</code> instance was created, it may or may
676not own its underlying <code>ArrayBuffer</code>. An <code>ArrayBuffer</code> must not
677be transferred unless it is known that the <code>Buffer</code> instance
678owns it. In particular, for <code>Buffer</code>s created from the internal
679<code>Buffer</code> pool (using, for instance <code>Buffer.from()</code> or <code>Buffer.alloc()</code>),
680transferring them is not possible and they will always be cloned,
681which sends a copy of the entire <code>Buffer</code> pool.
682This behavior may come with unintended higher memory
683usage and possible security concerns.</p>
684<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>
685<p>The <code>ArrayBuffer</code>s for <code>Buffer</code> instances created using
686<code>Buffer.alloc()</code> or <code>Buffer.allocUnsafeSlow()</code> can always be
687transferred but doing so will render all other existing views of
688those <code>ArrayBuffer</code>s unusable.</p>
689<h4><code>port.ref()</code><span><a class="mark" href="#worker_threads_port_ref" id="worker_threads_port_ref">#</a></span></h4>
690<div class="api_metadata">
691<span>Added in: v10.5.0</span>
692</div>
693<p>Opposite of <code>unref()</code>. Calling <code>ref()</code> on a previously <code>unref()</code>ed port will
694<em>not</em> let the program exit if it's the only active handle left (the default
695behavior). If the port is <code>ref()</code>ed, calling <code>ref()</code> again will have no effect.</p>
696<p>If listeners are attached or removed using <code>.on('message')</code>, the port will
697be <code>ref()</code>ed and <code>unref()</code>ed automatically depending on whether
698listeners for the event exist.</p>
699<h4><code>port.start()</code><span><a class="mark" href="#worker_threads_port_start" id="worker_threads_port_start">#</a></span></h4>
700<div class="api_metadata">
701<span>Added in: v10.5.0</span>
702</div>
703<p>Starts receiving messages on this <code>MessagePort</code>. When using this port
704as an event emitter, this will be called automatically once <code>'message'</code>
705listeners are attached.</p>
706<p>This method exists for parity with the Web <code>MessagePort</code> API. In Node.js,
707it is only useful for ignoring messages when no event listener is present.
708Node.js also diverges in its handling of <code>.onmessage</code>. Setting it will
709automatically call <code>.start()</code>, but unsetting it will let messages queue up
710until a new handler is set or the port is discarded.</p>
711<h4><code>port.unref()</code><span><a class="mark" href="#worker_threads_port_unref" id="worker_threads_port_unref">#</a></span></h4>
712<div class="api_metadata">
713<span>Added in: v10.5.0</span>
714</div>
715<p>Calling <code>unref()</code> on a port will allow the thread to exit if this is the only
716active handle in the event system. If the port is already <code>unref()</code>ed calling
717<code>unref()</code> again will have no effect.</p>
718<p>If listeners are attached or removed using <code>.on('message')</code>, the port will
719be <code>ref()</code>ed and <code>unref()</code>ed automatically depending on whether
720listeners for the event exist.</p>
721</section><section><h3>Class: <code>Worker</code><span><a class="mark" href="#worker_threads_class_worker" id="worker_threads_class_worker">#</a></span></h3>
722<div class="api_metadata">
723<span>Added in: v10.5.0</span>
724</div>
725<ul>
726<li>Extends: <a href="events.html#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
727</ul>
728<p>The <code>Worker</code> class represents an independent JavaScript execution thread.
729Most Node.js APIs are available inside of it.</p>
730<p>Notable differences inside a Worker environment are:</p>
731<ul>
732<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>
733may be redirected by the parent thread.</li>
734<li>The <a href="#worker_threads_worker_ismainthread"><code>require('worker_threads').isMainThread</code></a> property is set to <code>false</code>.</li>
735<li>The <a href="#worker_threads_worker_parentport"><code>require('worker_threads').parentPort</code></a> message port is available.</li>
736<li><a href="process.html#process_process_exit_code"><code>process.exit()</code></a> does not stop the whole program, just the single thread,
737and <a href="process.html#process_process_abort"><code>process.abort()</code></a> is not available.</li>
738<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
739are not available.</li>
740<li><a href="process.html#process_process_env"><code>process.env</code></a> is a copy of the parent thread's environment variables,
741unless otherwise specified. Changes to one copy will not be visible in other
742threads, and will not be visible to native add-ons (unless
743<a href="#worker_threads_worker_share_env"><code>worker.SHARE_ENV</code></a> has been passed as the <code>env</code> option to the
744<a href="#worker_threads_class_worker"><code>Worker</code></a> constructor).</li>
745<li><a href="process.html#process_process_title"><code>process.title</code></a> cannot be modified.</li>
746<li>Signals will not be delivered through <a href="process.html#process_signal_events"><code>process.on('...')</code></a>.</li>
747<li>Execution may stop at any point as a result of <a href="#worker_threads_worker_terminate"><code>worker.terminate()</code></a>
748being invoked.</li>
749<li>IPC channels from parent processes are not accessible.</li>
750<li>The <a href="tracing.html"><code>trace_events</code></a> module is not supported.</li>
751<li>Native add-ons can only be loaded from multiple threads if they fulfill
752<a href="addons.html#addons_worker_support">certain conditions</a>.</li>
753</ul>
754<p>Creating <code>Worker</code> instances inside of other <code>Worker</code>s is possible.</p>
755<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
756achieved through inter-thread message passing. Internally, a <code>Worker</code> has a
757built-in pair of <a href="#worker_threads_class_messageport"><code>MessagePort</code></a>s that are already associated with each other
758when the <code>Worker</code> is created. While the <code>MessagePort</code> object on the parent side
759is not directly exposed, its functionalities are exposed through
760<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
761on the <code>Worker</code> object for the parent thread.</p>
762<p>To create custom messaging channels (which is encouraged over using the default
763global channel because it facilitates separation of concerns), users can create
764a <code>MessageChannel</code> object on either thread and pass one of the
765<code>MessagePort</code>s on that <code>MessageChannel</code> to the other thread through a
766pre-existing channel, such as the global one.</p>
767<p>See <a href="#worker_threads_port_postmessage_value_transferlist"><code>port.postMessage()</code></a> for more information on how messages are passed,
768and what kind of JavaScript values can be successfully transported through
769the thread barrier.</p>
770<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>);
771<span class="hljs-keyword">const</span> {
772  <span class="hljs-title class_">Worker</span>, <span class="hljs-title class_">MessageChannel</span>, <span class="hljs-title class_">MessagePort</span>, isMainThread, parentPort
773} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);
774<span class="hljs-keyword">if</span> (isMainThread) {
775  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
776  <span class="hljs-keyword">const</span> subChannel = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
777  worker.<span class="hljs-title function_">postMessage</span>({ <span class="hljs-attr">hereIsYourPort</span>: subChannel.<span class="hljs-property">port1</span> }, [subChannel.<span class="hljs-property">port1</span>]);
778  subChannel.<span class="hljs-property">port2</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">value</span>) =></span> {
779    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'received:'</span>, value);
780  });
781} <span class="hljs-keyword">else</span> {
782  parentPort.<span class="hljs-title function_">once</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">value</span>) =></span> {
783    <span class="hljs-title function_">assert</span>(value.<span class="hljs-property">hereIsYourPort</span> <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">MessagePort</span>);
784    value.<span class="hljs-property">hereIsYourPort</span>.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'the worker is sending this'</span>);
785    value.<span class="hljs-property">hereIsYourPort</span>.<span class="hljs-title function_">close</span>();
786  });
787}</code></pre>
788<h4><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></h4>
789<div class="api_metadata">
790<details class="changelog"><summary>History</summary>
791<table>
792<tbody><tr><th>Version</th><th>Changes</th></tr>
793<tr><td>v14.9.0</td>
794<td><p>The <code>filename</code> parameter can be a WHATWG <code>URL</code> object using <code>data:</code> protocol.</p></td></tr>
795<tr><td>v14.9.0</td>
796<td><p>The <code>trackUnmanagedFds</code> option was set to <code>true</code> by default.</p></td></tr>
797<tr><td>v14.6.0</td>
798<td><p>The <code>trackUnmanagedFds</code> option was introduced.</p></td></tr>
799<tr><td>v14.0.0</td>
800<td><p>The <code>transferList</code> option was introduced.</p></td></tr>
801<tr><td>v13.12.0</td>
802<td><p>The <code>filename</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
803<tr><td>v13.4.0, v12.16.0</td>
804<td><p>The <code>argv</code> option was introduced.</p></td></tr>
805<tr><td>v13.2.0, v12.16.0</td>
806<td><p>The <code>resourceLimits</code> option was introduced.</p></td></tr>
807<tr><td>v10.5.0</td>
808<td><p><span>Added in: v10.5.0</span></p></td></tr>
809</tbody></table>
810</details>
811</div>
812<ul>
813<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="url.html#url_the_whatwg_url_api" class="type">&#x3C;URL></a> The path to the Worker’s main script or module. Must
814be either an absolute path or a relative path (i.e. relative to the
815current working directory) starting with <code>./</code> or <code>../</code>, or a WHATWG <code>URL</code>
816object using <code>file:</code> or <code>data:</code> protocol.
817When using a <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs"><code>data:</code> URL</a>, the data is interpreted based on MIME type using
818the <a href="esm.html#esm_data_imports">ECMAScript module loader</a>.
819If <code>options.eval</code> is <code>true</code>, this is a string containing JavaScript code
820rather than a path.</li>
821<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
822<ul>
823<li><code>argv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any[]></a> List of arguments which would be stringified and appended to
824<code>process.argv</code> in the worker. This is mostly similar to the <code>workerData</code>
825but the values will be available on the global <code>process.argv</code> as if they
826were passed as CLI options to the script.</li>
827<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> If set, specifies the initial value of <code>process.env</code> inside
828the Worker thread. As a special value, <a href="#worker_threads_worker_share_env"><code>worker.SHARE_ENV</code></a> may be used
829to specify that the parent thread and the child thread should share their
830environment variables; in that case, changes to one thread’s <code>process.env</code>
831object will affect the other thread as well. <strong>Default:</strong> <code>process.env</code>.</li>
832<li><code>eval</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code> and the first argument is a <code>string</code>, interpret
833the first argument to the constructor as a script that is executed once the
834worker is online.</li>
835<li><code>execArgv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> List of node CLI options passed to the worker.
836V8 options (such as <code>--max-old-space-size</code>) and options that affect the
837process (such as <code>--title</code>) are not supported. If set, this will be provided
838as <a href="process.html#process_process_execargv"><code>process.execArgv</code></a> inside the worker. By default, options will be
839inherited from the parent thread.</li>
840<li><code>stdin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If this is set to <code>true</code>, then <code>worker.stdin</code> will
841provide a writable stream whose contents will appear as <code>process.stdin</code>
842inside the Worker. By default, no data is provided.</li>
843<li><code>stdout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If this is set to <code>true</code>, then <code>worker.stdout</code> will
844not automatically be piped through to <code>process.stdout</code> in the parent.</li>
845<li><code>stderr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If this is set to <code>true</code>, then <code>worker.stderr</code> will
846not automatically be piped through to <code>process.stderr</code> in the parent.</li>
847<li><code>workerData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Any JavaScript value that will be cloned and made
848available as <a href="#worker_threads_worker_workerdata"><code>require('worker_threads').workerData</code></a>. The cloning will
849occur 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
850will be thrown if the object cannot be cloned (e.g. because it contains
851<code>function</code>s).</li>
852<li><code>trackUnmanagedFds</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If this is set to <code>true</code>, then the Worker will
853track raw file descriptors managed through <a href="fs.html#fs_fs_open_path_flags_mode_callback"><code>fs.open()</code></a> and
854<a href="fs.html#fs_fs_close_fd_callback"><code>fs.close()</code></a>, and close them when the Worker exits, similar to other
855resources like network sockets or file descriptors managed through
856the <a href="fs.html#fs_class_filehandle"><code>FileHandle</code></a> API. This option is automatically inherited by all
857nested <code>Worker</code>s. <strong>Default</strong>: <code>false</code>.</li>
858<li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a> If one or more <code>MessagePort</code>-like objects
859are passed in <code>workerData</code>, a <code>transferList</code> is required for those
860items 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.
861See <a href="#worker_threads_port_postmessage_value_transferlist"><code>port.postMessage()</code></a> for more information.</li>
862<li><code>resourceLimits</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> An optional set of resource limits for the new
863JS engine instance. Reaching these limits will lead to termination of the
864<code>Worker</code> instance. These limits only affect the JS engine, and no external
865data, including no <code>ArrayBuffer</code>s. Even if these limits are set, the process
866may still abort if it encounters a global out-of-memory situation.
867<ul>
868<li><code>maxOldGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The maximum size of the main heap in MB.</li>
869<li><code>maxYoungGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The maximum size of a heap space for
870recently created objects.</li>
871<li><code>codeRangeSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The size of a pre-allocated memory range
872used for generated code.</li>
873<li><code>stackSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The default maximum stack size for the thread.
874Small values may lead to unusable Worker instances. <strong>Default:</strong> <code>4</code>.</li>
875</ul>
876</li>
877</ul>
878</li>
879</ul>
880<h4>Event: <code>'error'</code><span><a class="mark" href="#worker_threads_event_error" id="worker_threads_event_error">#</a></span></h4>
881<div class="api_metadata">
882<span>Added in: v10.5.0</span>
883</div>
884<ul>
885<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
886</ul>
887<p>The <code>'error'</code> event is emitted if the worker thread throws an uncaught
888exception. In that case, the worker will be terminated.</p>
889<h4>Event: <code>'exit'</code><span><a class="mark" href="#worker_threads_event_exit" id="worker_threads_event_exit">#</a></span></h4>
890<div class="api_metadata">
891<span>Added in: v10.5.0</span>
892</div>
893<ul>
894<li><code>exitCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
895</ul>
896<p>The <code>'exit'</code> event is emitted once the worker has stopped. If the worker
897exited by calling <a href="process.html#process_process_exit_code"><code>process.exit()</code></a>, the <code>exitCode</code> parameter will be the
898passed exit code. If the worker was terminated, the <code>exitCode</code> parameter will
899be <code>1</code>.</p>
900<p>This is the final event emitted by any <code>Worker</code> instance.</p>
901<h4>Event: <code>'message'</code><span><a class="mark" href="#worker_threads_event_message_1" id="worker_threads_event_message_1">#</a></span></h4>
902<div class="api_metadata">
903<span>Added in: v10.5.0</span>
904</div>
905<ul>
906<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The transmitted value</li>
907</ul>
908<p>The <code>'message'</code> event is emitted when the worker thread has invoked
909<a href="#worker_threads_worker_postmessage_value_transferlist"><code>require('worker_threads').parentPort.postMessage()</code></a>.
910See the <a href="#worker_threads_event_message"><code>port.on('message')</code></a> event for more details.</p>
911<p>All messages sent from the worker thread will be emitted before the
912<a href="#worker_threads_event_exit"><code>'exit'</code> event</a> is emitted on the <code>Worker</code> object.</p>
913<h4>Event: <code>'messageerror'</code><span><a class="mark" href="#worker_threads_event_messageerror_1" id="worker_threads_event_messageerror_1">#</a></span></h4>
914<div class="api_metadata">
915<span>Added in: v14.5.0</span>
916</div>
917<ul>
918<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> An Error object</li>
919</ul>
920<p>The <code>'messageerror'</code> event is emitted when deserializing a message failed.</p>
921<h4>Event: <code>'online'</code><span><a class="mark" href="#worker_threads_event_online" id="worker_threads_event_online">#</a></span></h4>
922<div class="api_metadata">
923<span>Added in: v10.5.0</span>
924</div>
925<p>The <code>'online'</code> event is emitted when the worker thread has started executing
926JavaScript code.</p>
927<h4><code>worker.getHeapSnapshot()</code><span><a class="mark" href="#worker_threads_worker_getheapsnapshot" id="worker_threads_worker_getheapsnapshot">#</a></span></h4>
928<div class="api_metadata">
929<span>Added in: v13.9.0</span>
930</div>
931<ul>
932<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> A promise for a Readable Stream containing
933a V8 heap snapshot</li>
934</ul>
935<p>Returns a readable stream for a V8 snapshot of the current state of the Worker.
936See <a href="v8.html#v8_v8_getheapsnapshot"><code>v8.getHeapSnapshot()</code></a> for more details.</p>
937<p>If the Worker thread is no longer running, which may occur before the
938<a href="#worker_threads_event_exit"><code>'exit'</code> event</a> is emitted, the returned <code>Promise</code> will be rejected
939immediately with an <a href="errors.html#ERR_WORKER_NOT_RUNNING"><code>ERR_WORKER_NOT_RUNNING</code></a> error.</p>
940<h4><code>worker.performance</code><span><a class="mark" href="#worker_threads_worker_performance" id="worker_threads_worker_performance">#</a></span></h4>
941<div class="api_metadata">
942<span>Added in: v14.17.0</span>
943</div>
944<p>An object that can be used to query performance information from a worker
945instance. Similar to <a href="perf_hooks.html#perf_hooks_perf_hooks_performance"><code>perf_hooks.performance</code></a>.</p>
946<h5><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></h5>
947<div class="api_metadata">
948<span>Added in: v14.17.0</span>
949</div>
950<ul>
951<li><code>utilization1</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The result of a previous call to
952<code>eventLoopUtilization()</code>.</li>
953<li><code>utilization2</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The result of a previous call to
954<code>eventLoopUtilization()</code> prior to <code>utilization1</code>.</li>
955<li>Returns <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
956<ul>
957<li><code>idle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
958<li><code>active</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
959<li><code>utilization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
960</ul>
961</li>
962</ul>
963<p>The same call as <a href="perf_hooks.html#perf_hooks_performance_eventlooputilization_utilization1_utilization2"><code>perf_hooks</code> <code>eventLoopUtilization()</code></a>, except the values
964of the worker instance are returned.</p>
965<p>One difference is that, unlike the main thread, bootstrapping within a worker
966is done within the event loop. So the event loop utilization will be
967immediately available once the worker's script begins execution.</p>
968<p>An <code>idle</code> time that does not increase does not indicate that the worker is
969stuck in bootstrap. The following examples shows how the worker's entire
970lifetime will never accumulate any <code>idle</code> time, but is still be able to process
971messages.</p>
972<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, isMainThread, parentPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);
973
974<span class="hljs-keyword">if</span> (isMainThread) {
975  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
976  <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> {
977    worker.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'hi'</span>);
978    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(worker.<span class="hljs-property">performance</span>.<span class="hljs-title function_">eventLoopUtilization</span>());
979  }, <span class="hljs-number">100</span>).<span class="hljs-title function_">unref</span>();
980  <span class="hljs-keyword">return</span>;
981}
982
983parentPort.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'msg'</span>)).<span class="hljs-title function_">unref</span>();
984(<span class="hljs-keyword">function</span> <span class="hljs-title function_">r</span>(<span class="hljs-params">n</span>) {
985  <span class="hljs-keyword">if</span> (--n &#x3C; <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span>;
986  <span class="hljs-keyword">const</span> t = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>();
987  <span class="hljs-keyword">while</span> (<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>() - t &#x3C; <span class="hljs-number">300</span>);
988  <span class="hljs-title function_">setImmediate</span>(r, n);
989})(<span class="hljs-number">10</span>);</code></pre>
990<p>The event loop utilization of a worker is available only after the <a href="#worker_threads_event_online"><code>'online'</code>
991event</a> emitted, and if called before this, or after the <a href="#worker_threads_event_exit"><code>'exit'</code>
992event</a>, then all properties have the value of <code>0</code>.</p>
993<h4><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></h4>
994<div class="api_metadata">
995<span>Added in: v10.5.0</span>
996</div>
997<ul>
998<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
999<li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a></li>
1000</ul>
1001<p>Send a message to the worker that will be received via
1002<a href="#worker_threads_event_message"><code>require('worker_threads').parentPort.on('message')</code></a>.
1003See <a href="#worker_threads_port_postmessage_value_transferlist"><code>port.postMessage()</code></a> for more details.</p>
1004<h4><code>worker.ref()</code><span><a class="mark" href="#worker_threads_worker_ref" id="worker_threads_worker_ref">#</a></span></h4>
1005<div class="api_metadata">
1006<span>Added in: v10.5.0</span>
1007</div>
1008<p>Opposite of <code>unref()</code>, calling <code>ref()</code> on a previously <code>unref()</code>ed worker will
1009<em>not</em> let the program exit if it's the only active handle left (the default
1010behavior). If the worker is <code>ref()</code>ed, calling <code>ref()</code> again will have
1011no effect.</p>
1012<h4><code>worker.resourceLimits</code><span><a class="mark" href="#worker_threads_worker_resourcelimits_1" id="worker_threads_worker_resourcelimits_1">#</a></span></h4>
1013<div class="api_metadata">
1014<span>Added in: v13.2.0, v12.16.0</span>
1015</div>
1016<ul>
1017<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
1018<ul>
1019<li><code>maxYoungGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
1020<li><code>maxOldGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
1021<li><code>codeRangeSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
1022<li><code>stackSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
1023</ul>
1024</li>
1025</ul>
1026<p>Provides the set of JS engine resource constraints for this Worker thread.
1027If the <code>resourceLimits</code> option was passed to the <a href="#worker_threads_class_worker"><code>Worker</code></a> constructor,
1028this matches its values.</p>
1029<p>If the worker has stopped, the return value is an empty object.</p>
1030<h4><code>worker.stderr</code><span><a class="mark" href="#worker_threads_worker_stderr" id="worker_threads_worker_stderr">#</a></span></h4>
1031<div class="api_metadata">
1032<span>Added in: v10.5.0</span>
1033</div>
1034<ul>
1035<li><a href="stream.html#stream_class_stream_readable" class="type">&#x3C;stream.Readable></a></li>
1036</ul>
1037<p>This is a readable stream which contains data written to <a href="process.html#process_process_stderr"><code>process.stderr</code></a>
1038inside the worker thread. If <code>stderr: true</code> was not passed to the
1039<a href="#worker_threads_class_worker"><code>Worker</code></a> constructor, then data will be piped to the parent thread's
1040<a href="process.html#process_process_stderr"><code>process.stderr</code></a> stream.</p>
1041<h4><code>worker.stdin</code><span><a class="mark" href="#worker_threads_worker_stdin" id="worker_threads_worker_stdin">#</a></span></h4>
1042<div class="api_metadata">
1043<span>Added in: v10.5.0</span>
1044</div>
1045<ul>
1046<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> | <a href="stream.html#stream_class_stream_writable" class="type">&#x3C;stream.Writable></a></li>
1047</ul>
1048<p>If <code>stdin: true</code> was passed to the <a href="#worker_threads_class_worker"><code>Worker</code></a> constructor, this is a
1049writable stream. The data written to this stream will be made available in
1050the worker thread as <a href="process.html#process_process_stdin"><code>process.stdin</code></a>.</p>
1051<h4><code>worker.stdout</code><span><a class="mark" href="#worker_threads_worker_stdout" id="worker_threads_worker_stdout">#</a></span></h4>
1052<div class="api_metadata">
1053<span>Added in: v10.5.0</span>
1054</div>
1055<ul>
1056<li><a href="stream.html#stream_class_stream_readable" class="type">&#x3C;stream.Readable></a></li>
1057</ul>
1058<p>This is a readable stream which contains data written to <a href="process.html#process_process_stdout"><code>process.stdout</code></a>
1059inside the worker thread. If <code>stdout: true</code> was not passed to the
1060<a href="#worker_threads_class_worker"><code>Worker</code></a> constructor, then data will be piped to the parent thread's
1061<a href="process.html#process_process_stdout"><code>process.stdout</code></a> stream.</p>
1062<h4><code>worker.terminate()</code><span><a class="mark" href="#worker_threads_worker_terminate" id="worker_threads_worker_terminate">#</a></span></h4>
1063<div class="api_metadata">
1064<details class="changelog"><summary>History</summary>
1065<table>
1066<tbody><tr><th>Version</th><th>Changes</th></tr>
1067<tr><td>v12.5.0</td>
1068<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>
1069<tr><td>v10.5.0</td>
1070<td><p><span>Added in: v10.5.0</span></p></td></tr>
1071</tbody></table>
1072</details>
1073</div>
1074<ul>
1075<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
1076</ul>
1077<p>Stop all JavaScript execution in the worker thread as soon as possible.
1078Returns a Promise for the exit code that is fulfilled when the
1079<a href="#worker_threads_event_exit"><code>'exit'</code> event</a> is emitted.</p>
1080<h4><code>worker.threadId</code><span><a class="mark" href="#worker_threads_worker_threadid_1" id="worker_threads_worker_threadid_1">#</a></span></h4>
1081<div class="api_metadata">
1082<span>Added in: v10.5.0</span>
1083</div>
1084<ul>
1085<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
1086</ul>
1087<p>An integer identifier for the referenced thread. Inside the worker thread,
1088it is available as <a href="#worker_threads_worker_threadid"><code>require('worker_threads').threadId</code></a>.
1089This value is unique for each <code>Worker</code> instance inside a single process.</p>
1090<h4><code>worker.unref()</code><span><a class="mark" href="#worker_threads_worker_unref" id="worker_threads_worker_unref">#</a></span></h4>
1091<div class="api_metadata">
1092<span>Added in: v10.5.0</span>
1093</div>
1094<p>Calling <code>unref()</code> on a worker will allow the thread to exit if this is the only
1095active handle in the event system. If the worker is already <code>unref()</code>ed calling
1096<code>unref()</code> again will have no effect.</p>
1097</section><section><h3>Notes<span><a class="mark" href="#worker_threads_notes" id="worker_threads_notes">#</a></span></h3>
1098<h4>Synchronous blocking of stdio<span><a class="mark" href="#worker_threads_synchronous_blocking_of_stdio" id="worker_threads_synchronous_blocking_of_stdio">#</a></span></h4>
1099<p><code>Worker</code>s utilize message passing via <a href="worker_threads.html#worker_threads_class_messageport" class="type">&#x3C;MessagePort></a> to implement interactions
1100with <code>stdio</code>. This means that <code>stdio</code> output originating from a <code>Worker</code> can
1101get blocked by synchronous code on the receiving end that is blocking the
1102Node.js event loop.</p>
1103
1104<pre><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> {
1105  <span class="hljs-title class_">Worker</span>,
1106  isMainThread,
1107} <span class="hljs-keyword">from</span> <span class="hljs-string">'worker_threads'</span>;
1108
1109<span class="hljs-keyword">if</span> (isMainThread) {
1110  <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>));
1111  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>; n &#x3C; <span class="hljs-number">1e10</span>; n++) {}
1112} <span class="hljs-keyword">else</span> {
1113  <span class="hljs-comment">// This output will be blocked by the for loop in the main thread.</span>
1114  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo'</span>);
1115}</code><code class="language-js cjs"><span class="hljs-meta">'use strict'</span>;
1116
1117<span class="hljs-keyword">const</span> {
1118  <span class="hljs-title class_">Worker</span>,
1119  isMainThread,
1120} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);
1121
1122<span class="hljs-keyword">if</span> (isMainThread) {
1123  <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
1124  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>; n &#x3C; <span class="hljs-number">1e10</span>; n++) {}
1125} <span class="hljs-keyword">else</span> {
1126  <span class="hljs-comment">// This output will be blocked by the for loop in the main thread.</span>
1127  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo'</span>);
1128}</code></pre>
1129<h4>Launching worker threads from preload scripts<span><a class="mark" href="#worker_threads_launching_worker_threads_from_preload_scripts" id="worker_threads_launching_worker_threads_from_preload_scripts">#</a></span></h4>
1130<p>Take care when launching worker threads from preload scripts (scripts loaded
1131and run using the <code>-r</code> command line flag). Unless the <code>execArgv</code> option is
1132explicitly set, new Worker threads automatically inherit the command line flags
1133from the running process and will preload the same preload scripts as the main
1134thread. If the preload script unconditionally launches a worker thread, every
1135thread spawned will spawn another until the application crashes.</p></section>
1136        <!-- API END -->
1137      </div>
1138    </div>
1139  </div>
1140  <script>
1141    'use strict';
1142    {
1143      const kCustomPreference = 'customDarkTheme';
1144      const userSettings = sessionStorage.getItem(kCustomPreference);
1145      const themeToggleButton = document.getElementById('theme-toggle-btn');
1146      if (userSettings === null && window.matchMedia) {
1147        const mq = window.matchMedia('(prefers-color-scheme: dark)');
1148        if ('onchange' in mq) {
1149          function mqChangeListener(e) {
1150            document.body.classList.toggle('dark-mode', e.matches);
1151          }
1152          mq.addEventListener('change', mqChangeListener);
1153          if (themeToggleButton) {
1154            themeToggleButton.addEventListener('click', function() {
1155              mq.removeEventListener('change', mqChangeListener);
1156            }, { once: true });
1157          }
1158        }
1159        if (mq.matches) {
1160          document.body.classList.add('dark-mode');
1161        }
1162      } else if (userSettings === 'true') {
1163        document.body.classList.add('dark-mode');
1164      }
1165      if (themeToggleButton) {
1166        themeToggleButton.hidden = false;
1167        themeToggleButton.addEventListener('click', function() {
1168          sessionStorage.setItem(
1169            kCustomPreference,
1170            document.body.classList.toggle('dark-mode')
1171          );
1172        });
1173      }
1174    }
1175  </script>
1176</body>
1177</html>
1178