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