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