• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1{
2  "type": "module",
3  "source": "doc/api/worker_threads.md",
4  "modules": [
5    {
6      "textRaw": "Worker threads",
7      "name": "worker_threads",
8      "introduced_in": "v10.5.0",
9      "stability": 2,
10      "stabilityText": "Stable",
11      "desc": "<p><strong>Source Code:</strong> <a href=\"https://github.com/nodejs/node/blob/v14.21.2/lib/worker_threads.js\">lib/worker_threads.js</a></p>\n<p>The <code>worker_threads</code> module enables the use of threads that execute JavaScript\nin parallel. To access it:</p>\n<pre><code class=\"language-js\">const worker = require('worker_threads');\n</code></pre>\n<p>Workers (threads) are useful for performing CPU-intensive JavaScript operations.\nThey will not help much with I/O-intensive work. Node.js’s built-in asynchronous\nI/O operations are more efficient than Workers can be.</p>\n<p>Unlike <code>child_process</code> or <code>cluster</code>, <code>worker_threads</code> can share memory. They do\nso by transferring <code>ArrayBuffer</code> instances or sharing <code>SharedArrayBuffer</code>\ninstances.</p>\n<pre><code class=\"language-js\">const {\n  Worker, isMainThread, parentPort, workerData\n} = require('worker_threads');\n\nif (isMainThread) {\n  module.exports = function parseJSAsync(script) {\n    return new Promise((resolve, reject) => {\n      const worker = new Worker(__filename, {\n        workerData: script\n      });\n      worker.on('message', resolve);\n      worker.on('error', reject);\n      worker.on('exit', (code) => {\n        if (code !== 0)\n          reject(new Error(`Worker stopped with exit code ${code}`));\n      });\n    });\n  };\n} else {\n  const { parse } = require('some-js-parsing-library');\n  const script = workerData;\n  parentPort.postMessage(parse(script));\n}\n</code></pre>\n<p>The above example spawns a Worker thread for each <code>parse()</code> call. In actual\npractice, use a pool of Workers instead for these kinds of tasks. Otherwise, the\noverhead of creating Workers would likely exceed their benefit.</p>\n<p>When implementing a worker pool, use the <a href=\"async_hooks.html#async_hooks_class_asyncresource\"><code>AsyncResource</code></a> API to inform\ndiagnostic tools (e.g. in order to provide asynchronous stack traces) about the\ncorrelation between tasks and their outcomes. See\n<a href=\"async_hooks.html#async-resource-worker-pool\">\"Using <code>AsyncResource</code> for a <code>Worker</code> thread pool\"</a>\nin the <code>async_hooks</code> documentation for an example implementation.</p>\n<p>Worker threads inherit non-process-specific options by default. Refer to\n<a href=\"#worker_threads_new_worker_filename_options\"><code>Worker constructor options</code></a> to know how to customize worker thread options,\nspecifically <code>argv</code> and <code>execArgv</code> options.</p>",
12      "methods": [
13        {
14          "textRaw": "`worker.getEnvironmentData(key)`",
15          "type": "method",
16          "name": "getEnvironmentData",
17          "meta": {
18            "added": [
19              "v14.18.0"
20            ],
21            "changes": []
22          },
23          "stability": 1,
24          "stabilityText": "Experimental",
25          "signatures": [
26            {
27              "return": {
28                "textRaw": "Returns: {any}",
29                "name": "return",
30                "type": "any"
31              },
32              "params": [
33                {
34                  "textRaw": "`key` {any} Any arbitrary, cloneable JavaScript value that can be used as a {Map} key.",
35                  "name": "key",
36                  "type": "any",
37                  "desc": "Any arbitrary, cloneable JavaScript value that can be used as a {Map} key."
38                }
39              ]
40            }
41          ],
42          "desc": "<p>Within a worker thread, <code>worker.getEnvironmentData()</code> returns a clone\nof data passed to the spawning thread's <code>worker.setEnvironmentData()</code>.\nEvery new <code>Worker</code> receives its own copy of the environment data\nautomatically.</p>\n<pre><code class=\"language-js\">const {\n  Worker,\n  isMainThread,\n  setEnvironmentData,\n  getEnvironmentData,\n} = require('worker_threads');\n\nif (isMainThread) {\n  setEnvironmentData('Hello', 'World!');\n  const worker = new Worker(__filename);\n} else {\n  console.log(getEnvironmentData('Hello'));  // Prints 'World!'.\n}\n</code></pre>"
43        },
44        {
45          "textRaw": "`worker.markAsUntransferable(object)`",
46          "type": "method",
47          "name": "markAsUntransferable",
48          "meta": {
49            "added": [
50              "v14.5.0"
51            ],
52            "changes": []
53          },
54          "signatures": [
55            {
56              "params": []
57            }
58          ],
59          "desc": "<p>Mark an object as not transferable. If <code>object</code> occurs in the transfer list of\na <a href=\"#worker_threads_port_postmessage_value_transferlist\"><code>port.postMessage()</code></a> call, it will be ignored.</p>\n<p>In particular, this makes sense for objects that can be cloned, rather than\ntransferred, and which are used by other objects on the sending side.\nFor example, Node.js marks the <code>ArrayBuffer</code>s it uses for its\n<a href=\"buffer.html#buffer_static_method_buffer_allocunsafe_size\"><code>Buffer</code> pool</a> with this.</p>\n<p>This operation cannot be undone.</p>\n<pre><code class=\"language-js\">const { MessageChannel, markAsUntransferable } = require('worker_threads');\n\nconst pooledBuffer = new ArrayBuffer(8);\nconst typedArray1 = new Uint8Array(pooledBuffer);\nconst typedArray2 = new Float64Array(pooledBuffer);\n\nmarkAsUntransferable(pooledBuffer);\n\nconst { port1 } = new MessageChannel();\nport1.postMessage(typedArray1, [ typedArray1.buffer ]);\n\n// The following line prints the contents of typedArray1 -- it still owns\n// its memory and has been cloned, not transferred. Without\n// `markAsUntransferable()`, this would print an empty Uint8Array.\n// typedArray2 is intact as well.\nconsole.log(typedArray1);\nconsole.log(typedArray2);\n</code></pre>\n<p>There is no equivalent to this API in browsers.</p>"
60        },
61        {
62          "textRaw": "`worker.moveMessagePortToContext(port, contextifiedSandbox)`",
63          "type": "method",
64          "name": "moveMessagePortToContext",
65          "meta": {
66            "added": [
67              "v11.13.0"
68            ],
69            "changes": []
70          },
71          "signatures": [
72            {
73              "return": {
74                "textRaw": "Returns: {MessagePort}",
75                "name": "return",
76                "type": "MessagePort"
77              },
78              "params": [
79                {
80                  "textRaw": "`port` {MessagePort} The message port which will be transferred.",
81                  "name": "port",
82                  "type": "MessagePort",
83                  "desc": "The message port which will be transferred."
84                },
85                {
86                  "textRaw": "`contextifiedSandbox` {Object} A [contextified][] object as returned by the `vm.createContext()` method.",
87                  "name": "contextifiedSandbox",
88                  "type": "Object",
89                  "desc": "A [contextified][] object as returned by the `vm.createContext()` method."
90                }
91              ]
92            }
93          ],
94          "desc": "<p>Transfer a <code>MessagePort</code> to a different <a href=\"vm.html\"><code>vm</code></a> Context. The original <code>port</code>\nobject will be rendered unusable, and the returned <code>MessagePort</code> instance will\ntake its place.</p>\n<p>The returned <code>MessagePort</code> will be an object in the target context, and will\ninherit from its global <code>Object</code> class. Objects passed to the\n<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\nand inherit from its global <code>Object</code> class.</p>\n<p>However, the created <code>MessagePort</code> will no longer inherit from\n<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\nevents using it.</p>"
95        },
96        {
97          "textRaw": "`worker.receiveMessageOnPort(port)`",
98          "type": "method",
99          "name": "receiveMessageOnPort",
100          "meta": {
101            "added": [
102              "v12.3.0"
103            ],
104            "changes": []
105          },
106          "signatures": [
107            {
108              "return": {
109                "textRaw": "Returns: {Object|undefined}",
110                "name": "return",
111                "type": "Object|undefined"
112              },
113              "params": [
114                {
115                  "textRaw": "`port` {MessagePort}",
116                  "name": "port",
117                  "type": "MessagePort"
118                }
119              ]
120            }
121          ],
122          "desc": "<p>Receive a single message from a given <code>MessagePort</code>. If no message is available,\n<code>undefined</code> is returned, otherwise an object with a single <code>message</code> property\nthat contains the message payload, corresponding to the oldest message in the\n<code>MessagePort</code>’s queue.</p>\n<pre><code class=\"language-js\">const { MessageChannel, receiveMessageOnPort } = require('worker_threads');\nconst { port1, port2 } = new MessageChannel();\nport1.postMessage({ hello: 'world' });\n\nconsole.log(receiveMessageOnPort(port2));\n// Prints: { message: { hello: 'world' } }\nconsole.log(receiveMessageOnPort(port2));\n// Prints: undefined\n</code></pre>\n<p>When this function is used, no <code>'message'</code> event will be emitted and the\n<code>onmessage</code> listener will not be invoked.</p>"
123        },
124        {
125          "textRaw": "`worker.setEnvironmentData(key[, value])`",
126          "type": "method",
127          "name": "setEnvironmentData",
128          "meta": {
129            "added": [
130              "v14.18.0"
131            ],
132            "changes": []
133          },
134          "stability": 1,
135          "stabilityText": "Experimental",
136          "signatures": [
137            {
138              "params": [
139                {
140                  "textRaw": "`key` {any} Any arbitrary, cloneable JavaScript value that can be used as a {Map} key.",
141                  "name": "key",
142                  "type": "any",
143                  "desc": "Any arbitrary, cloneable JavaScript value that can be used as a {Map} key."
144                },
145                {
146                  "textRaw": "`value` {any} Any arbitrary, cloneable JavaScript value that will be cloned and passed automatically to all new `Worker` instances. If `value` is passed as `undefined`, any previously set value for the `key` will be deleted.",
147                  "name": "value",
148                  "type": "any",
149                  "desc": "Any arbitrary, cloneable JavaScript value that will be cloned and passed automatically to all new `Worker` instances. If `value` is passed as `undefined`, any previously set value for the `key` will be deleted."
150                }
151              ]
152            }
153          ],
154          "desc": "<p>The <code>worker.setEnvironmentData()</code> API sets the content of\n<code>worker.getEnvironmentData()</code> in the current thread and all new <code>Worker</code>\ninstances spawned from the current context.</p>"
155        }
156      ],
157      "properties": [
158        {
159          "textRaw": "`isMainThread` {boolean}",
160          "type": "boolean",
161          "name": "isMainThread",
162          "meta": {
163            "added": [
164              "v10.5.0"
165            ],
166            "changes": []
167          },
168          "desc": "<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>\n<pre><code class=\"language-js\">const { Worker, isMainThread } = require('worker_threads');\n\nif (isMainThread) {\n  // This re-loads the current file inside a Worker instance.\n  new Worker(__filename);\n} else {\n  console.log('Inside Worker!');\n  console.log(isMainThread);  // Prints 'false'.\n}\n</code></pre>"
169        },
170        {
171          "textRaw": "`parentPort` {null|MessagePort}",
172          "type": "null|MessagePort",
173          "name": "parentPort",
174          "meta": {
175            "added": [
176              "v10.5.0"
177            ],
178            "changes": []
179          },
180          "desc": "<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>\nallowing communication with the parent thread. Messages sent using\n<code>parentPort.postMessage()</code> will be available in the parent thread\nusing <code>worker.on('message')</code>, and messages sent from the parent thread\nusing <code>worker.postMessage()</code> will be available in this thread using\n<code>parentPort.on('message')</code>.</p>\n<pre><code class=\"language-js\">const { Worker, isMainThread, parentPort } = require('worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  worker.once('message', (message) => {\n    console.log(message);  // Prints 'Hello, world!'.\n  });\n  worker.postMessage('Hello, world!');\n} else {\n  // When a message from the parent thread is received, send it back:\n  parentPort.once('message', (message) => {\n    parentPort.postMessage(message);\n  });\n}\n</code></pre>"
181        },
182        {
183          "textRaw": "`resourceLimits` {Object}",
184          "type": "Object",
185          "name": "resourceLimits",
186          "meta": {
187            "added": [
188              "v13.2.0",
189              "v12.16.0"
190            ],
191            "changes": []
192          },
193          "options": [
194            {
195              "textRaw": "`maxYoungGenerationSizeMb` {number}",
196              "name": "maxYoungGenerationSizeMb",
197              "type": "number"
198            },
199            {
200              "textRaw": "`maxOldGenerationSizeMb` {number}",
201              "name": "maxOldGenerationSizeMb",
202              "type": "number"
203            },
204            {
205              "textRaw": "`codeRangeSizeMb` {number}",
206              "name": "codeRangeSizeMb",
207              "type": "number"
208            },
209            {
210              "textRaw": "`stackSizeMb` {number}",
211              "name": "stackSizeMb",
212              "type": "number"
213            }
214          ],
215          "desc": "<p>Provides the set of JS engine resource constraints inside this Worker thread.\nIf the <code>resourceLimits</code> option was passed to the <a href=\"#worker_threads_class_worker\"><code>Worker</code></a> constructor,\nthis matches its values.</p>\n<p>If this is used in the main thread, its value is an empty object.</p>"
216        },
217        {
218          "textRaw": "`SHARE_ENV` {symbol}",
219          "type": "symbol",
220          "name": "SHARE_ENV",
221          "meta": {
222            "added": [
223              "v11.14.0"
224            ],
225            "changes": []
226          },
227          "desc": "<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>\nconstructor, to indicate that the current thread and the Worker thread should\nshare read and write access to the same set of environment variables.</p>\n<pre><code class=\"language-js\">const { Worker, SHARE_ENV } = require('worker_threads');\nnew Worker('process.env.SET_IN_WORKER = \"foo\"', { eval: true, env: SHARE_ENV })\n  .on('exit', () => {\n    console.log(process.env.SET_IN_WORKER);  // Prints 'foo'.\n  });\n</code></pre>"
228        },
229        {
230          "textRaw": "`threadId` {integer}",
231          "type": "integer",
232          "name": "threadId",
233          "meta": {
234            "added": [
235              "v10.5.0"
236            ],
237            "changes": []
238          },
239          "desc": "<p>An integer identifier for the current thread. On the corresponding worker object\n(if there is any), it is available as <a href=\"#worker_threads_worker_threadid_1\"><code>worker.threadId</code></a>.\nThis value is unique for each <a href=\"#worker_threads_class_worker\"><code>Worker</code></a> instance inside a single process.</p>"
240        },
241        {
242          "textRaw": "`worker.workerData`",
243          "name": "workerData",
244          "meta": {
245            "added": [
246              "v10.5.0"
247            ],
248            "changes": []
249          },
250          "desc": "<p>An arbitrary JavaScript value that contains a clone of the data passed\nto this thread’s <code>Worker</code> constructor.</p>\n<p>The data is cloned as if using <a href=\"#worker_threads_port_postmessage_value_transferlist\"><code>postMessage()</code></a>,\naccording 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>\n<pre><code class=\"language-js\">const { Worker, isMainThread, workerData } = require('worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename, { workerData: 'Hello, world!' });\n} else {\n  console.log(workerData);  // Prints 'Hello, world!'.\n}\n</code></pre>"
251        }
252      ],
253      "classes": [
254        {
255          "textRaw": "Class: `MessageChannel`",
256          "type": "class",
257          "name": "MessageChannel",
258          "meta": {
259            "added": [
260              "v10.5.0"
261            ],
262            "changes": []
263          },
264          "desc": "<p>Instances of the <code>worker.MessageChannel</code> class represent an asynchronous,\ntwo-way communications channel.\nThe <code>MessageChannel</code> has no methods of its own. <code>new MessageChannel()</code>\nyields an object with <code>port1</code> and <code>port2</code> properties, which refer to linked\n<a href=\"#worker_threads_class_messageport\"><code>MessagePort</code></a> instances.</p>\n<pre><code class=\"language-js\">const { MessageChannel } = require('worker_threads');\n\nconst { port1, port2 } = new MessageChannel();\nport1.on('message', (message) => console.log('received', message));\nport2.postMessage({ foo: 'bar' });\n// Prints: received { foo: 'bar' } from the `port1.on('message')` listener\n</code></pre>"
265        },
266        {
267          "textRaw": "Class: `MessagePort`",
268          "type": "class",
269          "name": "MessagePort",
270          "meta": {
271            "added": [
272              "v10.5.0"
273            ],
274            "changes": [
275              {
276                "version": [
277                  "v14.7.0"
278                ],
279                "pr-url": "https://github.com/nodejs/node/pull/34057",
280                "description": "This class now inherits from `EventTarget` rather than from `EventEmitter`."
281              }
282            ]
283          },
284          "desc": "<ul>\n<li>Extends: <a href=\"events.html#events_class_eventtarget\" class=\"type\">&lt;EventTarget&gt;</a></li>\n</ul>\n<p>Instances of the <code>worker.MessagePort</code> class represent one end of an\nasynchronous, two-way communications channel. It can be used to transfer\nstructured data, memory regions and other <code>MessagePort</code>s between different\n<a href=\"#worker_threads_class_worker\"><code>Worker</code></a>s.</p>\n<p>This implementation matches <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/MessagePort\">browser <code>MessagePort</code></a>s.</p>",
285          "events": [
286            {
287              "textRaw": "Event: `'close'`",
288              "type": "event",
289              "name": "close",
290              "meta": {
291                "added": [
292                  "v10.5.0"
293                ],
294                "changes": []
295              },
296              "params": [],
297              "desc": "<p>The <code>'close'</code> event is emitted once either side of the channel has been\ndisconnected.</p>\n<pre><code class=\"language-js\">const { MessageChannel } = require('worker_threads');\nconst { port1, port2 } = new MessageChannel();\n\n// Prints:\n//   foobar\n//   closed!\nport2.on('message', (message) => console.log(message));\nport2.on('close', () => console.log('closed!'));\n\nport1.postMessage('foobar');\nport1.close();\n</code></pre>"
298            },
299            {
300              "textRaw": "Event: `'message'`",
301              "type": "event",
302              "name": "message",
303              "meta": {
304                "added": [
305                  "v10.5.0"
306                ],
307                "changes": []
308              },
309              "params": [
310                {
311                  "textRaw": "`value` {any} The transmitted value",
312                  "name": "value",
313                  "type": "any",
314                  "desc": "The transmitted value"
315                }
316              ],
317              "desc": "<p>The <code>'message'</code> event is emitted for any incoming message, containing the cloned\ninput of <a href=\"#worker_threads_port_postmessage_value_transferlist\"><code>port.postMessage()</code></a>.</p>\n<p>Listeners on this event will receive a clone of the <code>value</code> parameter as passed\nto <code>postMessage()</code> and no further arguments.</p>"
318            },
319            {
320              "textRaw": "Event: `'messageerror'`",
321              "type": "event",
322              "name": "messageerror",
323              "meta": {
324                "added": [
325                  "v14.5.0"
326                ],
327                "changes": []
328              },
329              "params": [
330                {
331                  "textRaw": "`error` {Error} An Error object",
332                  "name": "error",
333                  "type": "Error",
334                  "desc": "An Error object"
335                }
336              ],
337              "desc": "<p>The <code>'messageerror'</code> event is emitted when deserializing a message failed.</p>\n<p>Currently, this event is emitted when there is an error occurring while\ninstantiating the posted JS object on the receiving end. Such situations\nare rare, but can happen, for instance, when certain Node.js API objects\nare received in a <code>vm.Context</code> (where Node.js APIs are currently\nunavailable).</p>"
338            }
339          ],
340          "methods": [
341            {
342              "textRaw": "`port.close()`",
343              "type": "method",
344              "name": "close",
345              "meta": {
346                "added": [
347                  "v10.5.0"
348                ],
349                "changes": []
350              },
351              "signatures": [
352                {
353                  "params": []
354                }
355              ],
356              "desc": "<p>Disables further sending of messages on either side of the connection.\nThis method can be called when no further communication will happen over this\n<code>MessagePort</code>.</p>\n<p>The <a href=\"#worker_threads_event_close\"><code>'close'</code> event</a> will be emitted on both <code>MessagePort</code> instances that\nare part of the channel.</p>"
357            },
358            {
359              "textRaw": "`port.postMessage(value[, transferList])`",
360              "type": "method",
361              "name": "postMessage",
362              "meta": {
363                "added": [
364                  "v10.5.0"
365                ],
366                "changes": [
367                  {
368                    "version": "v14.18.0",
369                    "pr-url": "https://github.com/nodejs/node/pull/37917",
370                    "description": "Add 'BlockList' to the list of cloneable types."
371                  },
372                  {
373                    "version": "v14.18.0",
374                    "pr-url": "https://github.com/nodejs/node/pull/37155",
375                    "description": "Add 'Histogram' types to the list of cloneable types."
376                  },
377                  {
378                    "version": "v14.5.0",
379                    "pr-url": "https://github.com/nodejs/node/pull/33360",
380                    "description": "Added `KeyObject` to the list of cloneable types."
381                  },
382                  {
383                    "version": "v14.5.0",
384                    "pr-url": "https://github.com/nodejs/node/pull/33772",
385                    "description": "Added `FileHandle` to the list of transferable types."
386                  }
387                ]
388              },
389              "signatures": [
390                {
391                  "params": [
392                    {
393                      "textRaw": "`value` {any}",
394                      "name": "value",
395                      "type": "any"
396                    },
397                    {
398                      "textRaw": "`transferList` {Object[]}",
399                      "name": "transferList",
400                      "type": "Object[]"
401                    }
402                  ]
403                }
404              ],
405              "desc": "<p>Sends a JavaScript value to the receiving side of this channel.\n<code>value</code> will be transferred in a way which is compatible with\nthe <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm\">HTML structured clone algorithm</a>.</p>\n<p>In particular, the significant differences to <code>JSON</code> are:</p>\n<ul>\n<li><code>value</code> may contain circular references.</li>\n<li><code>value</code> may contain instances of builtin JS types such as <code>RegExp</code>s,\n<code>BigInt</code>s, <code>Map</code>s, <code>Set</code>s, etc.</li>\n<li><code>value</code> may contain typed arrays, both using <code>ArrayBuffer</code>s\nand <code>SharedArrayBuffer</code>s.</li>\n<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>\n<li><code>value</code> may not contain native (C++-backed) objects other than:\n<ul>\n<li><a href=\"fs.html#fs_class_filehandle\" class=\"type\">&lt;FileHandle&gt;</a>s,</li>\n<li><a href=\"perf_hooks.html#perf_hooks_class_histogram\" class=\"type\">&lt;Histogram&gt;</a>s,</li>\n<li><a href=\"crypto.html#crypto_class_keyobject\" class=\"type\">&lt;KeyObject&gt;</a>s,</li>\n<li><a href=\"worker_threads.html#worker_threads_class_messageport\" class=\"type\">&lt;MessagePort&gt;</a>s,</li>\n<li><a href=\"net.html#net_class_net_blocklist\" class=\"type\">&lt;net.BlockList&gt;</a>s,</li>\n<li><a href=\"net.html#net_class_net_socketaddress\" class=\"type\">&lt;net.SocketAddress&gt;</a>es,</li>\n</ul>\n</li>\n</ul>\n<pre><code class=\"language-js\">const { MessageChannel } = require('worker_threads');\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (message) => console.log(message));\n\nconst circularData = {};\ncircularData.foo = circularData;\n// Prints: { foo: [Circular] }\nport2.postMessage(circularData);\n</code></pre>\n<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\n<a href=\"fs.html#fs_class_filehandle\"><code>FileHandle</code></a> objects.\nAfter transferring, they will not be usable on the sending side of the channel\nanymore (even if they are not contained in <code>value</code>). Unlike with\n<a href=\"child_process.html\">child processes</a>, transferring handles such as network sockets is currently\nnot supported.</p>\n<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\nfrom either thread. They cannot be listed in <code>transferList</code>.</p>\n<p><code>value</code> may still contain <code>ArrayBuffer</code> instances that are not in\n<code>transferList</code>; in that case, the underlying memory is copied rather than moved.</p>\n<pre><code class=\"language-js\">const { MessageChannel } = require('worker_threads');\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (message) => console.log(message));\n\nconst uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);\n// This posts a copy of `uint8Array`:\nport2.postMessage(uint8Array);\n// This does not copy data, but renders `uint8Array` unusable:\nport2.postMessage(uint8Array, [ uint8Array.buffer ]);\n\n// The memory for the `sharedUint8Array` will be accessible from both the\n// original and the copy received by `.on('message')`:\nconst sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));\nport2.postMessage(sharedUint8Array);\n\n// This transfers a freshly created message port to the receiver.\n// This can be used, for example, to create communication channels between\n// multiple `Worker` threads that are children of the same parent thread.\nconst otherChannel = new MessageChannel();\nport2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);\n</code></pre>\n<p>Because the object cloning uses the structured clone algorithm,\nnon-enumerable properties, property accessors, and object prototypes are\nnot preserved. In particular, <a href=\"buffer.html\"><code>Buffer</code></a> objects will be read as\nplain <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>\n<p>The message object will be cloned immediately, and can be modified after\nposting without having side effects.</p>\n<p>For more information on the serialization and deserialization mechanisms\nbehind this API, see the <a href=\"v8.html#v8_serialization_api\">serialization API of the <code>v8</code> module</a>.</p>",
406              "modules": [
407                {
408                  "textRaw": "Considerations when transferring TypedArrays and Buffers",
409                  "name": "considerations_when_transferring_typedarrays_and_buffers",
410                  "desc": "<p>All <code>TypedArray</code> and <code>Buffer</code> instances are views over an underlying\n<code>ArrayBuffer</code>. That is, it is the <code>ArrayBuffer</code> that actually stores\nthe raw data while the <code>TypedArray</code> and <code>Buffer</code> objects provide a\nway of viewing and manipulating the data. It is possible and common\nfor multiple views to be created over the same <code>ArrayBuffer</code> instance.\nGreat care must be taken when using a transfer list to transfer an\n<code>ArrayBuffer</code> as doing so will cause all <code>TypedArray</code> and <code>Buffer</code>\ninstances that share that same <code>ArrayBuffer</code> to become unusable.</p>\n<pre><code class=\"language-js\">const ab = new ArrayBuffer(10);\n\nconst u1 = new Uint8Array(ab);\nconst u2 = new Uint16Array(ab);\n\nconsole.log(u2.length);  // prints 5\n\nport.postMessage(u1, [u1.buffer]);\n\nconsole.log(u2.length);  // prints 0\n</code></pre>\n<p>For <code>Buffer</code> instances, specifically, whether the underlying\n<code>ArrayBuffer</code> can be transferred or cloned depends entirely on how\ninstances were created, which often cannot be reliably determined.</p>\n<p>An <code>ArrayBuffer</code> can be marked with <a href=\"#worker_threads_worker_markasuntransferable_object\"><code>markAsUntransferable()</code></a> to indicate\nthat it should always be cloned and never transferred.</p>\n<p>Depending on how a <code>Buffer</code> instance was created, it may or may\nnot own its underlying <code>ArrayBuffer</code>. An <code>ArrayBuffer</code> must not\nbe transferred unless it is known that the <code>Buffer</code> instance\nowns it. In particular, for <code>Buffer</code>s created from the internal\n<code>Buffer</code> pool (using, for instance <code>Buffer.from()</code> or <code>Buffer.alloc()</code>),\ntransferring them is not possible and they will always be cloned,\nwhich sends a copy of the entire <code>Buffer</code> pool.\nThis behavior may come with unintended higher memory\nusage and possible security concerns.</p>\n<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>\n<p>The <code>ArrayBuffer</code>s for <code>Buffer</code> instances created using\n<code>Buffer.alloc()</code> or <code>Buffer.allocUnsafeSlow()</code> can always be\ntransferred but doing so will render all other existing views of\nthose <code>ArrayBuffer</code>s unusable.</p>",
411                  "type": "module",
412                  "displayName": "Considerations when transferring TypedArrays and Buffers"
413                }
414              ]
415            },
416            {
417              "textRaw": "`port.ref()`",
418              "type": "method",
419              "name": "ref",
420              "meta": {
421                "added": [
422                  "v10.5.0"
423                ],
424                "changes": []
425              },
426              "signatures": [
427                {
428                  "params": []
429                }
430              ],
431              "desc": "<p>Opposite of <code>unref()</code>. Calling <code>ref()</code> on a previously <code>unref()</code>ed port will\n<em>not</em> let the program exit if it's the only active handle left (the default\nbehavior). If the port is <code>ref()</code>ed, calling <code>ref()</code> again will have no effect.</p>\n<p>If listeners are attached or removed using <code>.on('message')</code>, the port will\nbe <code>ref()</code>ed and <code>unref()</code>ed automatically depending on whether\nlisteners for the event exist.</p>"
432            },
433            {
434              "textRaw": "`port.start()`",
435              "type": "method",
436              "name": "start",
437              "meta": {
438                "added": [
439                  "v10.5.0"
440                ],
441                "changes": []
442              },
443              "signatures": [
444                {
445                  "params": []
446                }
447              ],
448              "desc": "<p>Starts receiving messages on this <code>MessagePort</code>. When using this port\nas an event emitter, this will be called automatically once <code>'message'</code>\nlisteners are attached.</p>\n<p>This method exists for parity with the Web <code>MessagePort</code> API. In Node.js,\nit is only useful for ignoring messages when no event listener is present.\nNode.js also diverges in its handling of <code>.onmessage</code>. Setting it will\nautomatically call <code>.start()</code>, but unsetting it will let messages queue up\nuntil a new handler is set or the port is discarded.</p>"
449            },
450            {
451              "textRaw": "`port.unref()`",
452              "type": "method",
453              "name": "unref",
454              "meta": {
455                "added": [
456                  "v10.5.0"
457                ],
458                "changes": []
459              },
460              "signatures": [
461                {
462                  "params": []
463                }
464              ],
465              "desc": "<p>Calling <code>unref()</code> on a port will allow the thread to exit if this is the only\nactive handle in the event system. If the port is already <code>unref()</code>ed calling\n<code>unref()</code> again will have no effect.</p>\n<p>If listeners are attached or removed using <code>.on('message')</code>, the port will\nbe <code>ref()</code>ed and <code>unref()</code>ed automatically depending on whether\nlisteners for the event exist.</p>"
466            }
467          ]
468        },
469        {
470          "textRaw": "Class: `Worker`",
471          "type": "class",
472          "name": "Worker",
473          "meta": {
474            "added": [
475              "v10.5.0"
476            ],
477            "changes": []
478          },
479          "desc": "<ul>\n<li>Extends: <a href=\"events.html#events_class_eventemitter\" class=\"type\">&lt;EventEmitter&gt;</a></li>\n</ul>\n<p>The <code>Worker</code> class represents an independent JavaScript execution thread.\nMost Node.js APIs are available inside of it.</p>\n<p>Notable differences inside a Worker environment are:</p>\n<ul>\n<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>\nmay be redirected by the parent thread.</li>\n<li>The <a href=\"#worker_threads_worker_ismainthread\"><code>require('worker_threads').isMainThread</code></a> property is set to <code>false</code>.</li>\n<li>The <a href=\"#worker_threads_worker_parentport\"><code>require('worker_threads').parentPort</code></a> message port is available.</li>\n<li><a href=\"process.html#process_process_exit_code\"><code>process.exit()</code></a> does not stop the whole program, just the single thread,\nand <a href=\"process.html#process_process_abort\"><code>process.abort()</code></a> is not available.</li>\n<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\nare not available.</li>\n<li><a href=\"process.html#process_process_env\"><code>process.env</code></a> is a copy of the parent thread's environment variables,\nunless otherwise specified. Changes to one copy will not be visible in other\nthreads, and will not be visible to native add-ons (unless\n<a href=\"#worker_threads_worker_share_env\"><code>worker.SHARE_ENV</code></a> has been passed as the <code>env</code> option to the\n<a href=\"#worker_threads_class_worker\"><code>Worker</code></a> constructor).</li>\n<li><a href=\"process.html#process_process_title\"><code>process.title</code></a> cannot be modified.</li>\n<li>Signals will not be delivered through <a href=\"process.html#process_signal_events\"><code>process.on('...')</code></a>.</li>\n<li>Execution may stop at any point as a result of <a href=\"#worker_threads_worker_terminate\"><code>worker.terminate()</code></a>\nbeing invoked.</li>\n<li>IPC channels from parent processes are not accessible.</li>\n<li>The <a href=\"tracing.html\"><code>trace_events</code></a> module is not supported.</li>\n<li>Native add-ons can only be loaded from multiple threads if they fulfill\n<a href=\"addons.html#addons_worker_support\">certain conditions</a>.</li>\n</ul>\n<p>Creating <code>Worker</code> instances inside of other <code>Worker</code>s is possible.</p>\n<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\nachieved through inter-thread message passing. Internally, a <code>Worker</code> has a\nbuilt-in pair of <a href=\"#worker_threads_class_messageport\"><code>MessagePort</code></a>s that are already associated with each other\nwhen the <code>Worker</code> is created. While the <code>MessagePort</code> object on the parent side\nis not directly exposed, its functionalities are exposed through\n<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\non the <code>Worker</code> object for the parent thread.</p>\n<p>To create custom messaging channels (which is encouraged over using the default\nglobal channel because it facilitates separation of concerns), users can create\na <code>MessageChannel</code> object on either thread and pass one of the\n<code>MessagePort</code>s on that <code>MessageChannel</code> to the other thread through a\npre-existing channel, such as the global one.</p>\n<p>See <a href=\"#worker_threads_port_postmessage_value_transferlist\"><code>port.postMessage()</code></a> for more information on how messages are passed,\nand what kind of JavaScript values can be successfully transported through\nthe thread barrier.</p>\n<pre><code class=\"language-js\">const assert = require('assert');\nconst {\n  Worker, MessageChannel, MessagePort, isMainThread, parentPort\n} = require('worker_threads');\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  const subChannel = new MessageChannel();\n  worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]);\n  subChannel.port2.on('message', (value) => {\n    console.log('received:', value);\n  });\n} else {\n  parentPort.once('message', (value) => {\n    assert(value.hereIsYourPort instanceof MessagePort);\n    value.hereIsYourPort.postMessage('the worker is sending this');\n    value.hereIsYourPort.close();\n  });\n}\n</code></pre>",
480          "events": [
481            {
482              "textRaw": "Event: `'error'`",
483              "type": "event",
484              "name": "error",
485              "meta": {
486                "added": [
487                  "v10.5.0"
488                ],
489                "changes": []
490              },
491              "params": [
492                {
493                  "textRaw": "`err` {Error}",
494                  "name": "err",
495                  "type": "Error"
496                }
497              ],
498              "desc": "<p>The <code>'error'</code> event is emitted if the worker thread throws an uncaught\nexception. In that case, the worker will be terminated.</p>"
499            },
500            {
501              "textRaw": "Event: `'exit'`",
502              "type": "event",
503              "name": "exit",
504              "meta": {
505                "added": [
506                  "v10.5.0"
507                ],
508                "changes": []
509              },
510              "params": [
511                {
512                  "textRaw": "`exitCode` {integer}",
513                  "name": "exitCode",
514                  "type": "integer"
515                }
516              ],
517              "desc": "<p>The <code>'exit'</code> event is emitted once the worker has stopped. If the worker\nexited by calling <a href=\"process.html#process_process_exit_code\"><code>process.exit()</code></a>, the <code>exitCode</code> parameter will be the\npassed exit code. If the worker was terminated, the <code>exitCode</code> parameter will\nbe <code>1</code>.</p>\n<p>This is the final event emitted by any <code>Worker</code> instance.</p>"
518            },
519            {
520              "textRaw": "Event: `'message'`",
521              "type": "event",
522              "name": "message",
523              "meta": {
524                "added": [
525                  "v10.5.0"
526                ],
527                "changes": []
528              },
529              "params": [
530                {
531                  "textRaw": "`value` {any} The transmitted value",
532                  "name": "value",
533                  "type": "any",
534                  "desc": "The transmitted value"
535                }
536              ],
537              "desc": "<p>The <code>'message'</code> event is emitted when the worker thread has invoked\n<a href=\"#worker_threads_worker_postmessage_value_transferlist\"><code>require('worker_threads').parentPort.postMessage()</code></a>.\nSee the <a href=\"#worker_threads_event_message\"><code>port.on('message')</code></a> event for more details.</p>\n<p>All messages sent from the worker thread will be emitted before the\n<a href=\"#worker_threads_event_exit\"><code>'exit'</code> event</a> is emitted on the <code>Worker</code> object.</p>"
538            },
539            {
540              "textRaw": "Event: `'messageerror'`",
541              "type": "event",
542              "name": "messageerror",
543              "meta": {
544                "added": [
545                  "v14.5.0"
546                ],
547                "changes": []
548              },
549              "params": [
550                {
551                  "textRaw": "`error` {Error} An Error object",
552                  "name": "error",
553                  "type": "Error",
554                  "desc": "An Error object"
555                }
556              ],
557              "desc": "<p>The <code>'messageerror'</code> event is emitted when deserializing a message failed.</p>"
558            },
559            {
560              "textRaw": "Event: `'online'`",
561              "type": "event",
562              "name": "online",
563              "meta": {
564                "added": [
565                  "v10.5.0"
566                ],
567                "changes": []
568              },
569              "params": [],
570              "desc": "<p>The <code>'online'</code> event is emitted when the worker thread has started executing\nJavaScript code.</p>"
571            }
572          ],
573          "methods": [
574            {
575              "textRaw": "`worker.getHeapSnapshot()`",
576              "type": "method",
577              "name": "getHeapSnapshot",
578              "meta": {
579                "added": [
580                  "v13.9.0"
581                ],
582                "changes": []
583              },
584              "signatures": [
585                {
586                  "return": {
587                    "textRaw": "Returns: {Promise} A promise for a Readable Stream containing a V8 heap snapshot",
588                    "name": "return",
589                    "type": "Promise",
590                    "desc": "A promise for a Readable Stream containing a V8 heap snapshot"
591                  },
592                  "params": []
593                }
594              ],
595              "desc": "<p>Returns a readable stream for a V8 snapshot of the current state of the Worker.\nSee <a href=\"v8.html#v8_v8_getheapsnapshot\"><code>v8.getHeapSnapshot()</code></a> for more details.</p>\n<p>If the Worker thread is no longer running, which may occur before the\n<a href=\"#worker_threads_event_exit\"><code>'exit'</code> event</a> is emitted, the returned <code>Promise</code> will be rejected\nimmediately with an <a href=\"errors.html#ERR_WORKER_NOT_RUNNING\"><code>ERR_WORKER_NOT_RUNNING</code></a> error.</p>"
596            },
597            {
598              "textRaw": "`worker.postMessage(value[, transferList])`",
599              "type": "method",
600              "name": "postMessage",
601              "meta": {
602                "added": [
603                  "v10.5.0"
604                ],
605                "changes": []
606              },
607              "signatures": [
608                {
609                  "params": [
610                    {
611                      "textRaw": "`value` {any}",
612                      "name": "value",
613                      "type": "any"
614                    },
615                    {
616                      "textRaw": "`transferList` {Object[]}",
617                      "name": "transferList",
618                      "type": "Object[]"
619                    }
620                  ]
621                }
622              ],
623              "desc": "<p>Send a message to the worker that will be received via\n<a href=\"#worker_threads_event_message\"><code>require('worker_threads').parentPort.on('message')</code></a>.\nSee <a href=\"#worker_threads_port_postmessage_value_transferlist\"><code>port.postMessage()</code></a> for more details.</p>"
624            },
625            {
626              "textRaw": "`worker.ref()`",
627              "type": "method",
628              "name": "ref",
629              "meta": {
630                "added": [
631                  "v10.5.0"
632                ],
633                "changes": []
634              },
635              "signatures": [
636                {
637                  "params": []
638                }
639              ],
640              "desc": "<p>Opposite of <code>unref()</code>, calling <code>ref()</code> on a previously <code>unref()</code>ed worker will\n<em>not</em> let the program exit if it's the only active handle left (the default\nbehavior). If the worker is <code>ref()</code>ed, calling <code>ref()</code> again will have\nno effect.</p>"
641            },
642            {
643              "textRaw": "`worker.terminate()`",
644              "type": "method",
645              "name": "terminate",
646              "meta": {
647                "added": [
648                  "v10.5.0"
649                ],
650                "changes": [
651                  {
652                    "version": "v12.5.0",
653                    "pr-url": "https://github.com/nodejs/node/pull/28021",
654                    "description": "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."
655                  }
656                ]
657              },
658              "signatures": [
659                {
660                  "return": {
661                    "textRaw": "Returns: {Promise}",
662                    "name": "return",
663                    "type": "Promise"
664                  },
665                  "params": []
666                }
667              ],
668              "desc": "<p>Stop all JavaScript execution in the worker thread as soon as possible.\nReturns a Promise for the exit code that is fulfilled when the\n<a href=\"#worker_threads_event_exit\"><code>'exit'</code> event</a> is emitted.</p>"
669            },
670            {
671              "textRaw": "`worker.unref()`",
672              "type": "method",
673              "name": "unref",
674              "meta": {
675                "added": [
676                  "v10.5.0"
677                ],
678                "changes": []
679              },
680              "signatures": [
681                {
682                  "params": []
683                }
684              ],
685              "desc": "<p>Calling <code>unref()</code> on a worker will allow the thread to exit if this is the only\nactive handle in the event system. If the worker is already <code>unref()</code>ed calling\n<code>unref()</code> again will have no effect.</p>"
686            }
687          ],
688          "properties": [
689            {
690              "textRaw": "`worker.performance`",
691              "name": "performance",
692              "meta": {
693                "added": [
694                  "v14.17.0"
695                ],
696                "changes": []
697              },
698              "desc": "<p>An object that can be used to query performance information from a worker\ninstance. Similar to <a href=\"perf_hooks.html#perf_hooks_perf_hooks_performance\"><code>perf_hooks.performance</code></a>.</p>",
699              "methods": [
700                {
701                  "textRaw": "`performance.eventLoopUtilization([utilization1[, utilization2]])`",
702                  "type": "method",
703                  "name": "eventLoopUtilization",
704                  "meta": {
705                    "added": [
706                      "v14.17.0"
707                    ],
708                    "changes": []
709                  },
710                  "signatures": [
711                    {
712                      "return": {
713                        "textRaw": "Returns {Object}",
714                        "name": "return",
715                        "type": "Object",
716                        "options": [
717                          {
718                            "textRaw": "`idle` {number}",
719                            "name": "idle",
720                            "type": "number"
721                          },
722                          {
723                            "textRaw": "`active` {number}",
724                            "name": "active",
725                            "type": "number"
726                          },
727                          {
728                            "textRaw": "`utilization` {number}",
729                            "name": "utilization",
730                            "type": "number"
731                          }
732                        ]
733                      },
734                      "params": [
735                        {
736                          "textRaw": "`utilization1` {Object} The result of a previous call to `eventLoopUtilization()`.",
737                          "name": "utilization1",
738                          "type": "Object",
739                          "desc": "The result of a previous call to `eventLoopUtilization()`."
740                        },
741                        {
742                          "textRaw": "`utilization2` {Object} The result of a previous call to `eventLoopUtilization()` prior to `utilization1`.",
743                          "name": "utilization2",
744                          "type": "Object",
745                          "desc": "The result of a previous call to `eventLoopUtilization()` prior to `utilization1`."
746                        }
747                      ]
748                    }
749                  ],
750                  "desc": "<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\nof the worker instance are returned.</p>\n<p>One difference is that, unlike the main thread, bootstrapping within a worker\nis done within the event loop. So the event loop utilization will be\nimmediately available once the worker's script begins execution.</p>\n<p>An <code>idle</code> time that does not increase does not indicate that the worker is\nstuck in bootstrap. The following examples shows how the worker's entire\nlifetime will never accumulate any <code>idle</code> time, but is still be able to process\nmessages.</p>\n<pre><code class=\"language-js\">const { Worker, isMainThread, parentPort } = require('worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  setInterval(() => {\n    worker.postMessage('hi');\n    console.log(worker.performance.eventLoopUtilization());\n  }, 100).unref();\n  return;\n}\n\nparentPort.on('message', () => console.log('msg')).unref();\n(function r(n) {\n  if (--n &#x3C; 0) return;\n  const t = Date.now();\n  while (Date.now() - t &#x3C; 300);\n  setImmediate(r, n);\n})(10);\n</code></pre>\n<p>The event loop utilization of a worker is available only after the <a href=\"#worker_threads_event_online\"><code>'online'</code>\nevent</a> emitted, and if called before this, or after the <a href=\"#worker_threads_event_exit\"><code>'exit'</code>\nevent</a>, then all properties have the value of <code>0</code>.</p>"
751                }
752              ]
753            },
754            {
755              "textRaw": "`resourceLimits` {Object}",
756              "type": "Object",
757              "name": "resourceLimits",
758              "meta": {
759                "added": [
760                  "v13.2.0",
761                  "v12.16.0"
762                ],
763                "changes": []
764              },
765              "options": [
766                {
767                  "textRaw": "`maxYoungGenerationSizeMb` {number}",
768                  "name": "maxYoungGenerationSizeMb",
769                  "type": "number"
770                },
771                {
772                  "textRaw": "`maxOldGenerationSizeMb` {number}",
773                  "name": "maxOldGenerationSizeMb",
774                  "type": "number"
775                },
776                {
777                  "textRaw": "`codeRangeSizeMb` {number}",
778                  "name": "codeRangeSizeMb",
779                  "type": "number"
780                },
781                {
782                  "textRaw": "`stackSizeMb` {number}",
783                  "name": "stackSizeMb",
784                  "type": "number"
785                }
786              ],
787              "desc": "<p>Provides the set of JS engine resource constraints for this Worker thread.\nIf the <code>resourceLimits</code> option was passed to the <a href=\"#worker_threads_class_worker\"><code>Worker</code></a> constructor,\nthis matches its values.</p>\n<p>If the worker has stopped, the return value is an empty object.</p>"
788            },
789            {
790              "textRaw": "`stderr` {stream.Readable}",
791              "type": "stream.Readable",
792              "name": "stderr",
793              "meta": {
794                "added": [
795                  "v10.5.0"
796                ],
797                "changes": []
798              },
799              "desc": "<p>This is a readable stream which contains data written to <a href=\"process.html#process_process_stderr\"><code>process.stderr</code></a>\ninside the worker thread. If <code>stderr: true</code> was not passed to the\n<a href=\"#worker_threads_class_worker\"><code>Worker</code></a> constructor, then data will be piped to the parent thread's\n<a href=\"process.html#process_process_stderr\"><code>process.stderr</code></a> stream.</p>"
800            },
801            {
802              "textRaw": "`stdin` {null|stream.Writable}",
803              "type": "null|stream.Writable",
804              "name": "stdin",
805              "meta": {
806                "added": [
807                  "v10.5.0"
808                ],
809                "changes": []
810              },
811              "desc": "<p>If <code>stdin: true</code> was passed to the <a href=\"#worker_threads_class_worker\"><code>Worker</code></a> constructor, this is a\nwritable stream. The data written to this stream will be made available in\nthe worker thread as <a href=\"process.html#process_process_stdin\"><code>process.stdin</code></a>.</p>"
812            },
813            {
814              "textRaw": "`stdout` {stream.Readable}",
815              "type": "stream.Readable",
816              "name": "stdout",
817              "meta": {
818                "added": [
819                  "v10.5.0"
820                ],
821                "changes": []
822              },
823              "desc": "<p>This is a readable stream which contains data written to <a href=\"process.html#process_process_stdout\"><code>process.stdout</code></a>\ninside the worker thread. If <code>stdout: true</code> was not passed to the\n<a href=\"#worker_threads_class_worker\"><code>Worker</code></a> constructor, then data will be piped to the parent thread's\n<a href=\"process.html#process_process_stdout\"><code>process.stdout</code></a> stream.</p>"
824            },
825            {
826              "textRaw": "`threadId` {integer}",
827              "type": "integer",
828              "name": "threadId",
829              "meta": {
830                "added": [
831                  "v10.5.0"
832                ],
833                "changes": []
834              },
835              "desc": "<p>An integer identifier for the referenced thread. Inside the worker thread,\nit is available as <a href=\"#worker_threads_worker_threadid\"><code>require('worker_threads').threadId</code></a>.\nThis value is unique for each <code>Worker</code> instance inside a single process.</p>"
836            }
837          ],
838          "signatures": [
839            {
840              "params": [
841                {
842                  "textRaw": "`filename` {string|URL} The path to the Worker’s main script or module. Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with `./` or `../`, or a WHATWG `URL` object using `file:` or `data:` protocol. When using a [`data:` URL][], the data is interpreted based on MIME type using the [ECMAScript module loader][]. If `options.eval` is `true`, this is a string containing JavaScript code rather than a path.",
843                  "name": "filename",
844                  "type": "string|URL",
845                  "desc": "The path to the Worker’s main script or module. Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with `./` or `../`, or a WHATWG `URL` object using `file:` or `data:` protocol. When using a [`data:` URL][], the data is interpreted based on MIME type using the [ECMAScript module loader][]. If `options.eval` is `true`, this is a string containing JavaScript code rather than a path."
846                },
847                {
848                  "textRaw": "`options` {Object}",
849                  "name": "options",
850                  "type": "Object",
851                  "options": [
852                    {
853                      "textRaw": "`argv` {any[]} List of arguments which would be stringified and appended to `process.argv` in the worker. This is mostly similar to the `workerData` but the values will be available on the global `process.argv` as if they were passed as CLI options to the script.",
854                      "name": "argv",
855                      "type": "any[]",
856                      "desc": "List of arguments which would be stringified and appended to `process.argv` in the worker. This is mostly similar to the `workerData` but the values will be available on the global `process.argv` as if they were passed as CLI options to the script."
857                    },
858                    {
859                      "textRaw": "`env` {Object} If set, specifies the initial value of `process.env` inside the Worker thread. As a special value, [`worker.SHARE_ENV`][] may be used to specify that the parent thread and the child thread should share their environment variables; in that case, changes to one thread’s `process.env` object will affect the other thread as well. **Default:** `process.env`.",
860                      "name": "env",
861                      "type": "Object",
862                      "default": "`process.env`",
863                      "desc": "If set, specifies the initial value of `process.env` inside the Worker thread. As a special value, [`worker.SHARE_ENV`][] may be used to specify that the parent thread and the child thread should share their environment variables; in that case, changes to one thread’s `process.env` object will affect the other thread as well."
864                    },
865                    {
866                      "textRaw": "`eval` {boolean} If `true` and the first argument is a `string`, interpret the first argument to the constructor as a script that is executed once the worker is online.",
867                      "name": "eval",
868                      "type": "boolean",
869                      "desc": "If `true` and the first argument is a `string`, interpret the first argument to the constructor as a script that is executed once the worker is online."
870                    },
871                    {
872                      "textRaw": "`execArgv` {string[]} List of node CLI options passed to the worker. V8 options (such as `--max-old-space-size`) and options that affect the process (such as `--title`) are not supported. If set, this will be provided as [`process.execArgv`][] inside the worker. By default, options will be inherited from the parent thread.",
873                      "name": "execArgv",
874                      "type": "string[]",
875                      "desc": "List of node CLI options passed to the worker. V8 options (such as `--max-old-space-size`) and options that affect the process (such as `--title`) are not supported. If set, this will be provided as [`process.execArgv`][] inside the worker. By default, options will be inherited from the parent thread."
876                    },
877                    {
878                      "textRaw": "`stdin` {boolean} If this is set to `true`, then `worker.stdin` will provide a writable stream whose contents will appear as `process.stdin` inside the Worker. By default, no data is provided.",
879                      "name": "stdin",
880                      "type": "boolean",
881                      "desc": "If this is set to `true`, then `worker.stdin` will provide a writable stream whose contents will appear as `process.stdin` inside the Worker. By default, no data is provided."
882                    },
883                    {
884                      "textRaw": "`stdout` {boolean} If this is set to `true`, then `worker.stdout` will not automatically be piped through to `process.stdout` in the parent.",
885                      "name": "stdout",
886                      "type": "boolean",
887                      "desc": "If this is set to `true`, then `worker.stdout` will not automatically be piped through to `process.stdout` in the parent."
888                    },
889                    {
890                      "textRaw": "`stderr` {boolean} If this is set to `true`, then `worker.stderr` will not automatically be piped through to `process.stderr` in the parent.",
891                      "name": "stderr",
892                      "type": "boolean",
893                      "desc": "If this is set to `true`, then `worker.stderr` will not automatically be piped through to `process.stderr` in the parent."
894                    },
895                    {
896                      "textRaw": "`workerData` {any} Any JavaScript value that will be cloned and made available as [`require('worker_threads').workerData`][]. The cloning will occur as described in the [HTML structured clone algorithm][], and an error will be thrown if the object cannot be cloned (e.g. because it contains `function`s).",
897                      "name": "workerData",
898                      "type": "any",
899                      "desc": "Any JavaScript value that will be cloned and made available as [`require('worker_threads').workerData`][]. The cloning will occur as described in the [HTML structured clone algorithm][], and an error will be thrown if the object cannot be cloned (e.g. because it contains `function`s)."
900                    },
901                    {
902                      "textRaw": "`trackUnmanagedFds` {boolean} If this is set to `true`, then the Worker will track raw file descriptors managed through [`fs.open()`][] and [`fs.close()`][], and close them when the Worker exits, similar to other resources like network sockets or file descriptors managed through the [`FileHandle`][] API. This option is automatically inherited by all nested `Worker`s. **Default**: `false`.",
903                      "name": "trackUnmanagedFds",
904                      "type": "boolean",
905                      "desc": "If this is set to `true`, then the Worker will track raw file descriptors managed through [`fs.open()`][] and [`fs.close()`][], and close them when the Worker exits, similar to other resources like network sockets or file descriptors managed through the [`FileHandle`][] API. This option is automatically inherited by all nested `Worker`s. **Default**: `false`."
906                    },
907                    {
908                      "textRaw": "`transferList` {Object[]} If one or more `MessagePort`-like objects are passed in `workerData`, a `transferList` is required for those items or [`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`][] will be thrown. See [`port.postMessage()`][] for more information.",
909                      "name": "transferList",
910                      "type": "Object[]",
911                      "desc": "If one or more `MessagePort`-like objects are passed in `workerData`, a `transferList` is required for those items or [`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`][] will be thrown. See [`port.postMessage()`][] for more information."
912                    },
913                    {
914                      "textRaw": "`resourceLimits` {Object} An optional set of resource limits for the new JS engine instance. Reaching these limits will lead to termination of the `Worker` instance. These limits only affect the JS engine, and no external data, including no `ArrayBuffer`s. Even if these limits are set, the process may still abort if it encounters a global out-of-memory situation.",
915                      "name": "resourceLimits",
916                      "type": "Object",
917                      "desc": "An optional set of resource limits for the new JS engine instance. Reaching these limits will lead to termination of the `Worker` instance. These limits only affect the JS engine, and no external data, including no `ArrayBuffer`s. Even if these limits are set, the process may still abort if it encounters a global out-of-memory situation.",
918                      "options": [
919                        {
920                          "textRaw": "`maxOldGenerationSizeMb` {number} The maximum size of the main heap in MB.",
921                          "name": "maxOldGenerationSizeMb",
922                          "type": "number",
923                          "desc": "The maximum size of the main heap in MB."
924                        },
925                        {
926                          "textRaw": "`maxYoungGenerationSizeMb` {number} The maximum size of a heap space for recently created objects.",
927                          "name": "maxYoungGenerationSizeMb",
928                          "type": "number",
929                          "desc": "The maximum size of a heap space for recently created objects."
930                        },
931                        {
932                          "textRaw": "`codeRangeSizeMb` {number} The size of a pre-allocated memory range used for generated code.",
933                          "name": "codeRangeSizeMb",
934                          "type": "number",
935                          "desc": "The size of a pre-allocated memory range used for generated code."
936                        },
937                        {
938                          "textRaw": "`stackSizeMb` {number} The default maximum stack size for the thread. Small values may lead to unusable Worker instances. **Default:** `4`.",
939                          "name": "stackSizeMb",
940                          "type": "number",
941                          "default": "`4`",
942                          "desc": "The default maximum stack size for the thread. Small values may lead to unusable Worker instances."
943                        }
944                      ]
945                    }
946                  ]
947                }
948              ]
949            }
950          ]
951        }
952      ],
953      "modules": [
954        {
955          "textRaw": "Notes",
956          "name": "notes",
957          "modules": [
958            {
959              "textRaw": "Synchronous blocking of stdio",
960              "name": "synchronous_blocking_of_stdio",
961              "desc": "<p><code>Worker</code>s utilize message passing via <a href=\"worker_threads.html#worker_threads_class_messageport\" class=\"type\">&lt;MessagePort&gt;</a> to implement interactions\nwith <code>stdio</code>. This means that <code>stdio</code> output originating from a <code>Worker</code> can\nget blocked by synchronous code on the receiving end that is blocking the\nNode.js event loop.</p>\n<pre><code class=\"language-mjs\">import {\n  Worker,\n  isMainThread,\n} from 'worker_threads';\n\nif (isMainThread) {\n  new Worker(new URL(import.meta.url));\n  for (let n = 0; n &#x3C; 1e10; n++) {}\n} else {\n  // This output will be blocked by the for loop in the main thread.\n  console.log('foo');\n}\n</code></pre>\n<pre><code class=\"language-cjs\">'use strict';\n\nconst {\n  Worker,\n  isMainThread,\n} = require('worker_threads');\n\nif (isMainThread) {\n  new Worker(__filename);\n  for (let n = 0; n &#x3C; 1e10; n++) {}\n} else {\n  // This output will be blocked by the for loop in the main thread.\n  console.log('foo');\n}\n</code></pre>",
962              "type": "module",
963              "displayName": "Synchronous blocking of stdio"
964            },
965            {
966              "textRaw": "Launching worker threads from preload scripts",
967              "name": "launching_worker_threads_from_preload_scripts",
968              "desc": "<p>Take care when launching worker threads from preload scripts (scripts loaded\nand run using the <code>-r</code> command line flag). Unless the <code>execArgv</code> option is\nexplicitly set, new Worker threads automatically inherit the command line flags\nfrom the running process and will preload the same preload scripts as the main\nthread. If the preload script unconditionally launches a worker thread, every\nthread spawned will spawn another until the application crashes.</p>",
969              "type": "module",
970              "displayName": "Launching worker threads from preload scripts"
971            }
972          ],
973          "type": "module",
974          "displayName": "Notes"
975        }
976      ],
977      "type": "module",
978      "displayName": "Worker threads"
979    }
980  ]
981}