File: worker_threads.html

package info (click to toggle)
nodejs 22.14.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 246,928 kB
  • sloc: cpp: 1,582,349; javascript: 582,017; ansic: 82,400; python: 60,561; sh: 4,009; makefile: 2,263; asm: 1,732; pascal: 1,565; perl: 248; lisp: 222; xml: 42
file content (1730 lines) | stat: -rw-r--r-- 136,315 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <meta name="nodejs.org:node-version" content="v22.14.0">
  <title>Worker threads | Node.js v22.14.0 Documentation</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback">
  <link rel="stylesheet" href="assets/style.css">
  <link rel="stylesheet" href="assets/hljs.css">
  <link rel="canonical" href="https://nodejs.org/api/worker_threads.html">
  <script async defer src="assets/api.js" type="text/javascript"></script>
  <script>
      const storedTheme = localStorage.getItem('theme');

      // Follow operating system theme preference
      if (storedTheme === null && window.matchMedia) {
        const mq = window.matchMedia('(prefers-color-scheme: dark)');
        if (mq.matches) {
          document.documentElement.classList.add('dark-mode');
        }
      } else if (storedTheme === 'dark') {
        document.documentElement.classList.add('dark-mode');
      }
  </script>
  <style>@media(max-width:702px){.with-60-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:550px){.with-41-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:326px){.with-13-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}</style>
</head>
<body class="alt apidoc" id="api-section-worker_threads">
  <a href="#apicontent" class="skip-to-content">Skip to content</a>
  <div id="content" class="clearfix">
    <div role="navigation" id="column2" class="interior">
      <div id="intro" class="interior">
        <a href="/" title="Go back to the home page">
          Node.js
        </a>
      </div>
      <ul>
<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
</ul>
<hr class="line">
<ul>
<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li>
<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
<li><a href="console.html" class="nav-console">Console</a></li>
<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
<li><a href="dns.html" class="nav-dns">DNS</a></li>
<li><a href="domain.html" class="nav-domain">Domain</a></li>
<li><a href="errors.html" class="nav-errors">Errors</a></li>
<li><a href="events.html" class="nav-events">Events</a></li>
<li><a href="fs.html" class="nav-fs">File system</a></li>
<li><a href="globals.html" class="nav-globals">Globals</a></li>
<li><a href="http.html" class="nav-http">HTTP</a></li>
<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
<li><a href="https.html" class="nav-https">HTTPS</a></li>
<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li>
<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
<li><a href="typescript.html" class="nav-typescript">Modules: TypeScript</a></li>
<li><a href="net.html" class="nav-net">Net</a></li>
<li><a href="os.html" class="nav-os">OS</a></li>
<li><a href="path.html" class="nav-path">Path</a></li>
<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
<li><a href="process.html" class="nav-process">Process</a></li>
<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
<li><a href="readline.html" class="nav-readline">Readline</a></li>
<li><a href="repl.html" class="nav-repl">REPL</a></li>
<li><a href="report.html" class="nav-report">Report</a></li>
<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
<li><a href="sqlite.html" class="nav-sqlite">SQLite</a></li>
<li><a href="stream.html" class="nav-stream">Stream</a></li>
<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
<li><a href="test.html" class="nav-test">Test runner</a></li>
<li><a href="timers.html" class="nav-timers">Timers</a></li>
<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
<li><a href="tty.html" class="nav-tty">TTY</a></li>
<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
<li><a href="url.html" class="nav-url">URL</a></li>
<li><a href="util.html" class="nav-util">Utilities</a></li>
<li><a href="v8.html" class="nav-v8">V8</a></li>
<li><a href="vm.html" class="nav-vm">VM</a></li>
<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
<li><a href="worker_threads.html" class="nav-worker_threads active">Worker threads</a></li>
<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
</ul>
<hr class="line">
<ul>
<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
</ul>
    </div>

    <div id="column1" data-id="worker_threads" class="interior">
      <header class="header">
        <div class="header-container">
          <h1>Node.js v22.14.0 documentation</h1>
          <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden>
            <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24">
              <path fill="none" d="M0 0h24v24H0z" />
              <path d="M11.1 12.08c-2.33-4.51-.5-8.48.53-10.07C6.27 2.2 1.98 6.59 1.98 12c0 .14.02.28.02.42.62-.27 1.29-.42 2-.42 1.66 0 3.18.83 4.1 2.15A4.01 4.01 0 0111 18c0 1.52-.87 2.83-2.12 3.51.98.32 2.03.5 3.11.5 3.5 0 6.58-1.8 8.37-4.52-2.36.23-6.98-.97-9.26-5.41z"/>
              <path d="M7 16h-.18C6.4 14.84 5.3 14 4 14c-1.66 0-3 1.34-3 3s1.34 3 3 3h3c1.1 0 2-.9 2-2s-.9-2-2-2z"/>
            </svg>
            <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24">
              <path d="M0 0h24v24H0z" fill="none" />
              <path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/>
            </svg>
          </button>
        </div>
        <div id="gtoc">
          <ul>
            <li class="pinned-header">Node.js v22.14.0</li>
            
    <li class="picker-header">
      <a href="#toc-picker" aria-controls="toc-picker">
        <span class="picker-arrow"></span>
        Table of contents
      </a>

      <div class="picker" tabindex="-1"><div class="toc"><ul id="toc-picker">
<li><span class="stability_2"><a href="#worker-threads">Worker threads</a></span>
<ul>
<li><a href="#workergetenvironmentdatakey"><code>worker.getEnvironmentData(key)</code></a></li>
<li><a href="#workerisinternalthread"><code>worker.isInternalThread</code></a></li>
<li><a href="#workerismainthread"><code>worker.isMainThread</code></a></li>
<li><a href="#workermarkasuntransferableobject"><code>worker.markAsUntransferable(object)</code></a></li>
<li><a href="#workerismarkedasuntransferableobject"><code>worker.isMarkedAsUntransferable(object)</code></a></li>
<li><a href="#workermarkasuncloneableobject"><code>worker.markAsUncloneable(object)</code></a></li>
<li><a href="#workermovemessageporttocontextport-contextifiedsandbox"><code>worker.moveMessagePortToContext(port, contextifiedSandbox)</code></a></li>
<li><a href="#workerparentport"><code>worker.parentPort</code></a></li>
<li><span class="stability_1"><a href="#workerpostmessagetothreadthreadid-value-transferlist-timeout"><code>worker.postMessageToThread(threadId, value[, transferList][, timeout])</code></a></span></li>
<li><a href="#workerreceivemessageonportport"><code>worker.receiveMessageOnPort(port)</code></a></li>
<li><a href="#workerresourcelimits"><code>worker.resourceLimits</code></a></li>
<li><a href="#workershare_env"><code>worker.SHARE_ENV</code></a></li>
<li><a href="#workersetenvironmentdatakey-value"><code>worker.setEnvironmentData(key[, value])</code></a></li>
<li><a href="#workerthreadid"><code>worker.threadId</code></a></li>
<li><a href="#workerworkerdata"><code>worker.workerData</code></a></li>
<li><a href="#class-broadcastchannel-extends-eventtarget">Class: <code>BroadcastChannel extends EventTarget</code></a>
<ul>
<li><a href="#new-broadcastchannelname"><code>new BroadcastChannel(name)</code></a></li>
<li><a href="#broadcastchannelclose"><code>broadcastChannel.close()</code></a></li>
<li><a href="#broadcastchannelonmessage"><code>broadcastChannel.onmessage</code></a></li>
<li><a href="#broadcastchannelonmessageerror"><code>broadcastChannel.onmessageerror</code></a></li>
<li><a href="#broadcastchannelpostmessagemessage"><code>broadcastChannel.postMessage(message)</code></a></li>
<li><a href="#broadcastchannelref"><code>broadcastChannel.ref()</code></a></li>
<li><a href="#broadcastchannelunref"><code>broadcastChannel.unref()</code></a></li>
</ul>
</li>
<li><a href="#class-messagechannel">Class: <code>MessageChannel</code></a></li>
<li><a href="#class-messageport">Class: <code>MessagePort</code></a>
<ul>
<li><a href="#event-close">Event: <code>'close'</code></a></li>
<li><a href="#event-message">Event: <code>'message'</code></a></li>
<li><a href="#event-messageerror">Event: <code>'messageerror'</code></a></li>
<li><a href="#portclose"><code>port.close()</code></a></li>
<li><a href="#portpostmessagevalue-transferlist"><code>port.postMessage(value[, transferList])</code></a>
<ul>
<li><a href="#considerations-when-transferring-typedarrays-and-buffers">Considerations when transferring TypedArrays and Buffers</a></li>
<li><a href="#considerations-when-cloning-objects-with-prototypes-classes-and-accessors">Considerations when cloning objects with prototypes, classes, and accessors</a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#porthasref"><code>port.hasRef()</code></a></span></li>
<li><a href="#portref"><code>port.ref()</code></a></li>
<li><a href="#portstart"><code>port.start()</code></a></li>
<li><a href="#portunref"><code>port.unref()</code></a></li>
</ul>
</li>
<li><a href="#class-worker">Class: <code>Worker</code></a>
<ul>
<li><a href="#new-workerfilename-options"><code>new Worker(filename[, options])</code></a></li>
<li><a href="#event-error">Event: <code>'error'</code></a></li>
<li><a href="#event-exit">Event: <code>'exit'</code></a></li>
<li><a href="#event-message_1">Event: <code>'message'</code></a></li>
<li><a href="#event-messageerror_1">Event: <code>'messageerror'</code></a></li>
<li><a href="#event-online">Event: <code>'online'</code></a></li>
<li><a href="#workergetheapsnapshotoptions"><code>worker.getHeapSnapshot([options])</code></a></li>
<li><a href="#workerperformance"><code>worker.performance</code></a>
<ul>
<li><a href="#performanceeventlooputilizationutilization1-utilization2"><code>performance.eventLoopUtilization([utilization1[, utilization2]])</code></a></li>
</ul>
</li>
<li><a href="#workerpostmessagevalue-transferlist"><code>worker.postMessage(value[, transferList])</code></a></li>
<li><a href="#workerref"><code>worker.ref()</code></a></li>
<li><a href="#workerresourcelimits_1"><code>worker.resourceLimits</code></a></li>
<li><a href="#workerstderr"><code>worker.stderr</code></a></li>
<li><a href="#workerstdin"><code>worker.stdin</code></a></li>
<li><a href="#workerstdout"><code>worker.stdout</code></a></li>
<li><a href="#workerterminate"><code>worker.terminate()</code></a></li>
<li><a href="#workerthreadid_1"><code>worker.threadId</code></a></li>
<li><a href="#workerunref"><code>worker.unref()</code></a></li>
</ul>
</li>
<li><a href="#notes">Notes</a>
<ul>
<li><a href="#synchronous-blocking-of-stdio">Synchronous blocking of stdio</a></li>
<li><a href="#launching-worker-threads-from-preload-scripts">Launching worker threads from preload scripts</a></li>
</ul>
</li>
</ul>
</li>
</ul></div></div>
    </li>
  
            
    <li class="picker-header">
      <a href="#gtoc-picker" aria-controls="gtoc-picker">
        <span class="picker-arrow"></span>
        Index
      </a>

      <div class="picker" tabindex="-1" id="gtoc-picker"><ul>
<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>

      <li>
        <a href="index.html">Index</a>
      </li>
    </ul>
  
<hr class="line">
<ul>
<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li>
<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
<li><a href="console.html" class="nav-console">Console</a></li>
<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
<li><a href="dns.html" class="nav-dns">DNS</a></li>
<li><a href="domain.html" class="nav-domain">Domain</a></li>
<li><a href="errors.html" class="nav-errors">Errors</a></li>
<li><a href="events.html" class="nav-events">Events</a></li>
<li><a href="fs.html" class="nav-fs">File system</a></li>
<li><a href="globals.html" class="nav-globals">Globals</a></li>
<li><a href="http.html" class="nav-http">HTTP</a></li>
<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
<li><a href="https.html" class="nav-https">HTTPS</a></li>
<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li>
<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
<li><a href="typescript.html" class="nav-typescript">Modules: TypeScript</a></li>
<li><a href="net.html" class="nav-net">Net</a></li>
<li><a href="os.html" class="nav-os">OS</a></li>
<li><a href="path.html" class="nav-path">Path</a></li>
<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
<li><a href="process.html" class="nav-process">Process</a></li>
<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
<li><a href="readline.html" class="nav-readline">Readline</a></li>
<li><a href="repl.html" class="nav-repl">REPL</a></li>
<li><a href="report.html" class="nav-report">Report</a></li>
<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
<li><a href="sqlite.html" class="nav-sqlite">SQLite</a></li>
<li><a href="stream.html" class="nav-stream">Stream</a></li>
<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
<li><a href="test.html" class="nav-test">Test runner</a></li>
<li><a href="timers.html" class="nav-timers">Timers</a></li>
<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
<li><a href="tty.html" class="nav-tty">TTY</a></li>
<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
<li><a href="url.html" class="nav-url">URL</a></li>
<li><a href="util.html" class="nav-util">Utilities</a></li>
<li><a href="v8.html" class="nav-v8">V8</a></li>
<li><a href="vm.html" class="nav-vm">VM</a></li>
<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
<li><a href="worker_threads.html" class="nav-worker_threads active">Worker threads</a></li>
<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
</ul>
<hr class="line">
<ul>
<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
</ul></div>
    </li>
  
            
    <li class="picker-header">
      <a href="#alt-docs" aria-controls="alt-docs">
        <span class="picker-arrow"></span>
        Other versions
      </a>
      <div class="picker" tabindex="-1"><ol id="alt-docs"><li><a href="https://nodejs.org/docs/latest-v23.x/api/worker_threads.html">23.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v22.x/api/worker_threads.html">22.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v21.x/api/worker_threads.html">21.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v20.x/api/worker_threads.html">20.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v19.x/api/worker_threads.html">19.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v18.x/api/worker_threads.html">18.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v17.x/api/worker_threads.html">17.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v16.x/api/worker_threads.html">16.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v15.x/api/worker_threads.html">15.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v14.x/api/worker_threads.html">14.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v13.x/api/worker_threads.html">13.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v12.x/api/worker_threads.html">12.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v11.x/api/worker_threads.html">11.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v10.x/api/worker_threads.html">10.x</a></li></ol></div>
    </li>
  
            <li class="picker-header">
              <a href="#options-picker" aria-controls="options-picker">
                <span class="picker-arrow"></span>
                Options
              </a>
        
              <div class="picker" tabindex="-1">
                <ul id="options-picker">
                  <li>
                    <a href="all.html">View on single page</a>
                  </li>
                  <li>
                    <a href="worker_threads.json">View as JSON</a>
                  </li>
                  <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/main/doc/api/worker_threads.md">Edit on GitHub</a></li>    
                </ul>
              </div>
            </li>
          </ul>
        </div>
        <hr>
      </header>

      <details role="navigation" id="toc" open><summary>Table of contents</summary><ul>
<li><span class="stability_2"><a href="#worker-threads">Worker threads</a></span>
<ul>
<li><a href="#workergetenvironmentdatakey"><code>worker.getEnvironmentData(key)</code></a></li>
<li><a href="#workerisinternalthread"><code>worker.isInternalThread</code></a></li>
<li><a href="#workerismainthread"><code>worker.isMainThread</code></a></li>
<li><a href="#workermarkasuntransferableobject"><code>worker.markAsUntransferable(object)</code></a></li>
<li><a href="#workerismarkedasuntransferableobject"><code>worker.isMarkedAsUntransferable(object)</code></a></li>
<li><a href="#workermarkasuncloneableobject"><code>worker.markAsUncloneable(object)</code></a></li>
<li><a href="#workermovemessageporttocontextport-contextifiedsandbox"><code>worker.moveMessagePortToContext(port, contextifiedSandbox)</code></a></li>
<li><a href="#workerparentport"><code>worker.parentPort</code></a></li>
<li><span class="stability_1"><a href="#workerpostmessagetothreadthreadid-value-transferlist-timeout"><code>worker.postMessageToThread(threadId, value[, transferList][, timeout])</code></a></span></li>
<li><a href="#workerreceivemessageonportport"><code>worker.receiveMessageOnPort(port)</code></a></li>
<li><a href="#workerresourcelimits"><code>worker.resourceLimits</code></a></li>
<li><a href="#workershare_env"><code>worker.SHARE_ENV</code></a></li>
<li><a href="#workersetenvironmentdatakey-value"><code>worker.setEnvironmentData(key[, value])</code></a></li>
<li><a href="#workerthreadid"><code>worker.threadId</code></a></li>
<li><a href="#workerworkerdata"><code>worker.workerData</code></a></li>
<li><a href="#class-broadcastchannel-extends-eventtarget">Class: <code>BroadcastChannel extends EventTarget</code></a>
<ul>
<li><a href="#new-broadcastchannelname"><code>new BroadcastChannel(name)</code></a></li>
<li><a href="#broadcastchannelclose"><code>broadcastChannel.close()</code></a></li>
<li><a href="#broadcastchannelonmessage"><code>broadcastChannel.onmessage</code></a></li>
<li><a href="#broadcastchannelonmessageerror"><code>broadcastChannel.onmessageerror</code></a></li>
<li><a href="#broadcastchannelpostmessagemessage"><code>broadcastChannel.postMessage(message)</code></a></li>
<li><a href="#broadcastchannelref"><code>broadcastChannel.ref()</code></a></li>
<li><a href="#broadcastchannelunref"><code>broadcastChannel.unref()</code></a></li>
</ul>
</li>
<li><a href="#class-messagechannel">Class: <code>MessageChannel</code></a></li>
<li><a href="#class-messageport">Class: <code>MessagePort</code></a>
<ul>
<li><a href="#event-close">Event: <code>'close'</code></a></li>
<li><a href="#event-message">Event: <code>'message'</code></a></li>
<li><a href="#event-messageerror">Event: <code>'messageerror'</code></a></li>
<li><a href="#portclose"><code>port.close()</code></a></li>
<li><a href="#portpostmessagevalue-transferlist"><code>port.postMessage(value[, transferList])</code></a>
<ul>
<li><a href="#considerations-when-transferring-typedarrays-and-buffers">Considerations when transferring TypedArrays and Buffers</a></li>
<li><a href="#considerations-when-cloning-objects-with-prototypes-classes-and-accessors">Considerations when cloning objects with prototypes, classes, and accessors</a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#porthasref"><code>port.hasRef()</code></a></span></li>
<li><a href="#portref"><code>port.ref()</code></a></li>
<li><a href="#portstart"><code>port.start()</code></a></li>
<li><a href="#portunref"><code>port.unref()</code></a></li>
</ul>
</li>
<li><a href="#class-worker">Class: <code>Worker</code></a>
<ul>
<li><a href="#new-workerfilename-options"><code>new Worker(filename[, options])</code></a></li>
<li><a href="#event-error">Event: <code>'error'</code></a></li>
<li><a href="#event-exit">Event: <code>'exit'</code></a></li>
<li><a href="#event-message_1">Event: <code>'message'</code></a></li>
<li><a href="#event-messageerror_1">Event: <code>'messageerror'</code></a></li>
<li><a href="#event-online">Event: <code>'online'</code></a></li>
<li><a href="#workergetheapsnapshotoptions"><code>worker.getHeapSnapshot([options])</code></a></li>
<li><a href="#workerperformance"><code>worker.performance</code></a>
<ul>
<li><a href="#performanceeventlooputilizationutilization1-utilization2"><code>performance.eventLoopUtilization([utilization1[, utilization2]])</code></a></li>
</ul>
</li>
<li><a href="#workerpostmessagevalue-transferlist"><code>worker.postMessage(value[, transferList])</code></a></li>
<li><a href="#workerref"><code>worker.ref()</code></a></li>
<li><a href="#workerresourcelimits_1"><code>worker.resourceLimits</code></a></li>
<li><a href="#workerstderr"><code>worker.stderr</code></a></li>
<li><a href="#workerstdin"><code>worker.stdin</code></a></li>
<li><a href="#workerstdout"><code>worker.stdout</code></a></li>
<li><a href="#workerterminate"><code>worker.terminate()</code></a></li>
<li><a href="#workerthreadid_1"><code>worker.threadId</code></a></li>
<li><a href="#workerunref"><code>worker.unref()</code></a></li>
</ul>
</li>
<li><a href="#notes">Notes</a>
<ul>
<li><a href="#synchronous-blocking-of-stdio">Synchronous blocking of stdio</a></li>
<li><a href="#launching-worker-threads-from-preload-scripts">Launching worker threads from preload scripts</a></li>
</ul>
</li>
</ul>
</li>
</ul></details>

      <div role="main" id="apicontent">
        <h2>Worker threads<span><a class="mark" href="#worker-threads" id="worker-threads">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_threads"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="documentation.html#stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v22.14.0/lib/worker_threads.js">lib/worker_threads.js</a></p>
<p>The <code>node:worker_threads</code> module enables the use of threads that execute
JavaScript in parallel. To access it:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> worker = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);</code> <button class="copy-button">copy</button></pre>
<p>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.</p>
<p>Unlike <code>child_process</code> or <code>cluster</code>, <code>worker_threads</code> can share memory. They do
so by transferring <code>ArrayBuffer</code> instances or sharing <code>SharedArrayBuffer</code>
instances.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> {
  <span class="hljs-title class_">Worker</span>, isMainThread, parentPort, workerData,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-keyword">function</span> <span class="hljs-title function_">parseJSAsync</span>(<span class="hljs-params">script</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
      <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename, {
        <span class="hljs-attr">workerData</span>: script,
      });
      worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, resolve);
      worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, reject);
      worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
        <span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</span>)
          <span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">`Worker stopped with exit code <span class="hljs-subst">${code}</span>`</span>));
      });
    });
  };
} <span class="hljs-keyword">else</span> {
  <span class="hljs-keyword">const</span> { parse } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'some-js-parsing-library'</span>);
  <span class="hljs-keyword">const</span> script = workerData;
  parentPort.<span class="hljs-title function_">postMessage</span>(<span class="hljs-title function_">parse</span>(script));
}</code> <button class="copy-button">copy</button></pre>
<p>The above example spawns a Worker thread for each <code>parseJSAsync()</code> call. In
practice, use a pool of Workers for these kinds of tasks. Otherwise, the
overhead of creating Workers would likely exceed their benefit.</p>
<p>When implementing a worker pool, use the <a href="async_hooks.html#class-asyncresource"><code>AsyncResource</code></a> API to inform
diagnostic tools (e.g. to provide asynchronous stack traces) about the
correlation between tasks and their outcomes. See
<a href="async_context.html#using-asyncresource-for-a-worker-thread-pool">"Using <code>AsyncResource</code> for a <code>Worker</code> thread pool"</a>
in the <code>async_hooks</code> documentation for an example implementation.</p>
<p>Worker threads inherit non-process-specific options by default. Refer to
<a href="#new-workerfilename-options"><code>Worker constructor options</code></a> to know how to customize worker thread options,
specifically <code>argv</code> and <code>execArgv</code> options.</p>
<section><h3><code>worker.getEnvironmentData(key)</code><span><a class="mark" href="#workergetenvironmentdatakey" id="workergetenvironmentdatakey">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_getenvironmentdata_key"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v15.12.0, v14.18.0</td>
<td><p><span>Added in: v15.12.0, v14.18.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Any arbitrary, cloneable JavaScript value that can be used as a
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map" class="type">&#x3C;Map></a> key.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Within a worker thread, <code>worker.getEnvironmentData()</code> returns a clone
of data passed to the spawning thread's <code>worker.setEnvironmentData()</code>.
Every new <code>Worker</code> receives its own copy of the environment data
automatically.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> {
  <span class="hljs-title class_">Worker</span>,
  isMainThread,
  setEnvironmentData,
  getEnvironmentData,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-title function_">setEnvironmentData</span>(<span class="hljs-string">'Hello'</span>, <span class="hljs-string">'World!'</span>);
  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getEnvironmentData</span>(<span class="hljs-string">'Hello'</span>));  <span class="hljs-comment">// Prints 'World!'.</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>worker.isInternalThread</code><span><a class="mark" href="#workerisinternalthread" id="workerisinternalthread">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_isinternalthread"></a></h3>
<div class="api_metadata">
<span>Added in: v22.14.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Is <code>true</code> if this code is running inside of an internal <a href="#class-worker"><code>Worker</code></a> thread (e.g the loader thread).</p>
<pre><code class="language-bash">node --experimental-loader ./loader.js main.js</code> <button class="copy-button">copy</button></pre>

<pre class="with-60-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-comment">// loader.js</span>
<span class="hljs-keyword">const</span> { isInternalThread } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(isInternalThread);  <span class="hljs-comment">// true</span></code><code class="language-js mjs"><span class="hljs-comment">// loader.js</span>
<span class="hljs-keyword">import</span> { isInternalThread } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(isInternalThread);  <span class="hljs-comment">// true</span></code><button class="copy-button">copy</button></pre>

<pre class="with-60-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-comment">// main.js</span>
<span class="hljs-keyword">const</span> { isInternalThread } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(isInternalThread);  <span class="hljs-comment">// false</span></code><code class="language-js mjs"><span class="hljs-comment">// main.js</span>
<span class="hljs-keyword">import</span> { isInternalThread } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(isInternalThread);  <span class="hljs-comment">// false</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>worker.isMainThread</code><span><a class="mark" href="#workerismainthread" id="workerismainthread">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_ismainthread"></a></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Is <code>true</code> if this code is not running inside of a <a href="#class-worker"><code>Worker</code></a> thread.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, isMainThread } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-comment">// This re-loads the current file inside a Worker instance.</span>
  <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Inside Worker!'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(isMainThread);  <span class="hljs-comment">// Prints 'false'.</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>worker.markAsUntransferable(object)</code><span><a class="mark" href="#workermarkasuntransferableobject" id="workermarkasuntransferableobject">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_markasuntransferable_object"></a></h3>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.0</span>
</div>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Any arbitrary JavaScript value.</li>
</ul>
<p>Mark an object as not transferable. If <code>object</code> occurs in the transfer list of
a <a href="#portpostmessagevalue-transferlist"><code>port.postMessage()</code></a> call, an error is thrown. This is a no-op if
<code>object</code> is a primitive value.</p>
<p>In particular, this makes sense for objects that can be cloned, rather than
transferred, and which are used by other objects on the sending side.
For example, Node.js marks the <code>ArrayBuffer</code>s it uses for its
<a href="buffer.html#static-method-bufferallocunsafesize"><code>Buffer</code> pool</a> with this.</p>
<p>This operation cannot be undone.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span>, markAsUntransferable } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">const</span> pooledBuffer = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">8</span>);
<span class="hljs-keyword">const</span> typedArray1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(pooledBuffer);
<span class="hljs-keyword">const</span> typedArray2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>(pooledBuffer);

<span class="hljs-title function_">markAsUntransferable</span>(pooledBuffer);

<span class="hljs-keyword">const</span> { port1 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
<span class="hljs-keyword">try</span> {
  <span class="hljs-comment">// This will throw an error, because pooledBuffer is not transferable.</span>
  port1.<span class="hljs-title function_">postMessage</span>(typedArray1, [ typedArray1.<span class="hljs-property">buffer</span> ]);
} <span class="hljs-keyword">catch</span> (error) {
  <span class="hljs-comment">// error.name === 'DataCloneError'</span>
}

<span class="hljs-comment">// The following line prints the contents of typedArray1 -- it still owns</span>
<span class="hljs-comment">// its memory and has not been transferred. Without</span>
<span class="hljs-comment">// `markAsUntransferable()`, this would print an empty Uint8Array and the</span>
<span class="hljs-comment">// postMessage call would have succeeded.</span>
<span class="hljs-comment">// typedArray2 is intact as well.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(typedArray1);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(typedArray2);</code> <button class="copy-button">copy</button></pre>
<p>There is no equivalent to this API in browsers.</p>
</section><section><h3><code>worker.isMarkedAsUntransferable(object)</code><span><a class="mark" href="#workerismarkedasuntransferableobject" id="workerismarkedasuntransferableobject">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_ismarkedasuntransferable_object"></a></h3>
<div class="api_metadata">
<span>Added in: v21.0.0</span>
</div>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Any JavaScript value.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Check if an object is marked as not transferable with
<a href="#workermarkasuntransferableobject"><code>markAsUntransferable()</code></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { markAsUntransferable, isMarkedAsUntransferable } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">const</span> pooledBuffer = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">8</span>);
<span class="hljs-title function_">markAsUntransferable</span>(pooledBuffer);

<span class="hljs-title function_">isMarkedAsUntransferable</span>(pooledBuffer);  <span class="hljs-comment">// Returns true.</span></code> <button class="copy-button">copy</button></pre>
<p>There is no equivalent to this API in browsers.</p>
</section><section><h3><code>worker.markAsUncloneable(object)</code><span><a class="mark" href="#workermarkasuncloneableobject" id="workermarkasuncloneableobject">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_markasuncloneable_object"></a></h3>
<div class="api_metadata">
<span>Added in: v22.10.0</span>
</div>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Any arbitrary JavaScript value.</li>
</ul>
<p>Mark an object as not cloneable. If <code>object</code> is used as <a href="#event-message"><code>message</code></a> in
a <a href="#portpostmessagevalue-transferlist"><code>port.postMessage()</code></a> call, an error is thrown. This is a no-op if <code>object</code> is a
primitive value.</p>
<p>This has no effect on <code>ArrayBuffer</code>, or any <code>Buffer</code> like objects.</p>
<p>This operation cannot be undone.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { markAsUncloneable } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">const</span> anyObject = { <span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span> };
<span class="hljs-title function_">markAsUncloneable</span>(anyObject);
<span class="hljs-keyword">const</span> { port1 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
<span class="hljs-keyword">try</span> {
  <span class="hljs-comment">// This will throw an error, because anyObject is not cloneable.</span>
  port1.<span class="hljs-title function_">postMessage</span>(anyObject);
} <span class="hljs-keyword">catch</span> (error) {
  <span class="hljs-comment">// error.name === 'DataCloneError'</span>
}</code> <button class="copy-button">copy</button></pre>
<p>There is no equivalent to this API in browsers.</p>
</section><section><h3><code>worker.moveMessagePortToContext(port, contextifiedSandbox)</code><span><a class="mark" href="#workermovemessageporttocontextport-contextifiedsandbox" id="workermovemessageporttocontextport-contextifiedsandbox">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_movemessageporttocontext_port_contextifiedsandbox"></a></h3>
<div class="api_metadata">
<span>Added in: v11.13.0</span>
</div>
<ul>
<li>
<p><code>port</code> <a href="worker_threads.html#class-messageport" class="type">&#x3C;MessagePort></a> The message port to transfer.</p>
</li>
<li>
<p><code>contextifiedSandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> A <a href="vm.html#what-does-it-mean-to-contextify-an-object">contextified</a> object as returned by the
<code>vm.createContext()</code> method.</p>
</li>
<li>
<p>Returns: <a href="worker_threads.html#class-messageport" class="type">&#x3C;MessagePort></a></p>
</li>
</ul>
<p>Transfer a <code>MessagePort</code> to a different <a href="vm.html"><code>vm</code></a> Context. The original <code>port</code>
object is rendered unusable, and the returned <code>MessagePort</code> instance
takes its place.</p>
<p>The returned <code>MessagePort</code> is an object in the target context and
inherits from its global <code>Object</code> class. Objects passed to the
<a href="https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage"><code>port.onmessage()</code></a> listener are also created in the target context
and inherit from its global <code>Object</code> class.</p>
<p>However, the created <code>MessagePort</code> no longer inherits from
<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
events using it.</p>
</section><section><h3><code>worker.parentPort</code><span><a class="mark" href="#workerparentport" id="workerparentport">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_parentport"></a></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> | <a href="worker_threads.html#class-messageport" class="type">&#x3C;MessagePort></a></li>
</ul>
<p>If this thread is a <a href="#class-worker"><code>Worker</code></a>, this is a <a href="#class-messageport"><code>MessagePort</code></a>
allowing communication with the parent thread. Messages sent using
<code>parentPort.postMessage()</code> are available in the parent thread
using <code>worker.on('message')</code>, and messages sent from the parent thread
using <code>worker.postMessage()</code> are available in this thread using
<code>parentPort.on('message')</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, isMainThread, parentPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
  worker.<span class="hljs-title function_">once</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message);  <span class="hljs-comment">// Prints 'Hello, world!'.</span>
  });
  worker.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'Hello, world!'</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// When a message from the parent thread is received, send it back:</span>
  parentPort.<span class="hljs-title function_">once</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> {
    parentPort.<span class="hljs-title function_">postMessage</span>(message);
  });
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>worker.postMessageToThread(threadId, value[, transferList][, timeout])</code><span><a class="mark" href="#workerpostmessagetothreadthreadid-value-transferlist-timeout" id="workerpostmessagetothreadthreadid-value-transferlist-timeout">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_postmessagetothread_threadid_value_transferlist_timeout"></a></h3>
<div class="api_metadata">
<span>Added in: v22.5.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<ul>
<li><code>threadId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The target thread ID. If the thread ID is invalid, a
<a href="errors.html#err_worker_messaging_failed"><code>ERR_WORKER_MESSAGING_FAILED</code></a> error will be thrown. If the target thread ID is the current thread ID,
a <a href="errors.html#err_worker_messaging_same_thread"><code>ERR_WORKER_MESSAGING_SAME_THREAD</code></a> error will be thrown.</li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The value to send.</li>
<li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a> If one or more <code>MessagePort</code>-like objects are passed in <code>value</code>,
a <code>transferList</code> is required for those items or <a href="errors.html#err_missing_message_port_in_transfer_list"><code>ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST</code></a> is thrown.
See <a href="#portpostmessagevalue-transferlist"><code>port.postMessage()</code></a> for more information.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Time to wait for the message to be delivered in milliseconds.
By default it's <code>undefined</code>, which means wait forever. If the operation times out,
a <a href="errors.html#err_worker_messaging_timeout"><code>ERR_WORKER_MESSAGING_TIMEOUT</code></a> error is thrown.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> A promise which is fulfilled if the message was successfully processed by destination thread.</li>
</ul>
<p>Sends a value to another worker, identified by its thread ID.</p>
<p>If the target thread has no listener for the <code>workerMessage</code> event, then the operation will throw
a <a href="errors.html#err_worker_messaging_failed"><code>ERR_WORKER_MESSAGING_FAILED</code></a> error.</p>
<p>If the target thread threw an error while processing the <code>workerMessage</code> event, then the operation will throw
a <a href="errors.html#err_worker_messaging_errored"><code>ERR_WORKER_MESSAGING_ERRORED</code></a> error.</p>
<p>This method should be used when the target thread is not the direct
parent or child of the current thread.
If the two threads are parent-children, use the <a href="#workerpostmessagevalue-transferlist"><code>require('node:worker_threads').parentPort.postMessage()</code></a>
and the <a href="#workerpostmessagevalue-transferlist"><code>worker.postMessage()</code></a> to let the threads communicate.</p>
<p>The example below shows the use of of <code>postMessageToThread</code>: it creates 10 nested threads,
the last one will try to communicate with the main thread.</p>

<pre class="with-41-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { fileURLToPath } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">import</span> {
  postMessageToThread,
  threadId,
  workerData,
  <span class="hljs-title class_">Worker</span>,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;

<span class="hljs-keyword">const</span> channel = <span class="hljs-keyword">new</span> <span class="hljs-title class_">BroadcastChannel</span>(<span class="hljs-string">'sync'</span>);
<span class="hljs-keyword">const</span> level = workerData?.<span class="hljs-property">level</span> ?? <span class="hljs-number">0</span>;

<span class="hljs-keyword">if</span> (level &#x3C; <span class="hljs-number">10</span>) {
  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(<span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>), {
    <span class="hljs-attr">workerData</span>: { <span class="hljs-attr">level</span>: level + <span class="hljs-number">1</span> },
  });
}

<span class="hljs-keyword">if</span> (level === <span class="hljs-number">0</span>) {
  process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'workerMessage'</span>, <span class="hljs-function">(<span class="hljs-params">value, source</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${source}</span> -> <span class="hljs-subst">${threadId}</span>:`</span>, value);
    <span class="hljs-title function_">postMessageToThread</span>(source, { <span class="hljs-attr">message</span>: <span class="hljs-string">'pong'</span> });
  });
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (level === <span class="hljs-number">10</span>) {
  process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'workerMessage'</span>, <span class="hljs-function">(<span class="hljs-params">value, source</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${source}</span> -> <span class="hljs-subst">${threadId}</span>:`</span>, value);
    channel.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'done'</span>);
    channel.<span class="hljs-title function_">close</span>();
  });

  <span class="hljs-keyword">await</span> <span class="hljs-title function_">postMessageToThread</span>(<span class="hljs-number">0</span>, { <span class="hljs-attr">message</span>: <span class="hljs-string">'ping'</span> });
}

channel.<span class="hljs-property">onmessage</span> = channel.<span class="hljs-property">close</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  postMessageToThread,
  threadId,
  workerData,
  <span class="hljs-title class_">Worker</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">const</span> channel = <span class="hljs-keyword">new</span> <span class="hljs-title class_">BroadcastChannel</span>(<span class="hljs-string">'sync'</span>);
<span class="hljs-keyword">const</span> level = workerData?.<span class="hljs-property">level</span> ?? <span class="hljs-number">0</span>;

<span class="hljs-keyword">if</span> (level &#x3C; <span class="hljs-number">10</span>) {
  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename, {
    <span class="hljs-attr">workerData</span>: { <span class="hljs-attr">level</span>: level + <span class="hljs-number">1</span> },
  });
}

<span class="hljs-keyword">if</span> (level === <span class="hljs-number">0</span>) {
  process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'workerMessage'</span>, <span class="hljs-function">(<span class="hljs-params">value, source</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${source}</span> -> <span class="hljs-subst">${threadId}</span>:`</span>, value);
    <span class="hljs-title function_">postMessageToThread</span>(source, { <span class="hljs-attr">message</span>: <span class="hljs-string">'pong'</span> });
  });
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (level === <span class="hljs-number">10</span>) {
  process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'workerMessage'</span>, <span class="hljs-function">(<span class="hljs-params">value, source</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${source}</span> -> <span class="hljs-subst">${threadId}</span>:`</span>, value);
    channel.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'done'</span>);
    channel.<span class="hljs-title function_">close</span>();
  });

  <span class="hljs-title function_">postMessageToThread</span>(<span class="hljs-number">0</span>, { <span class="hljs-attr">message</span>: <span class="hljs-string">'ping'</span> });
}

channel.<span class="hljs-property">onmessage</span> = channel.<span class="hljs-property">close</span>;</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>worker.receiveMessageOnPort(port)</code><span><a class="mark" href="#workerreceivemessageonportport" id="workerreceivemessageonportport">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_receivemessageonport_port"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.12.0</td>
<td><p>The port argument can also refer to a <code>BroadcastChannel</code> now.</p></td></tr>
<tr><td>v12.3.0</td>
<td><p><span>Added in: v12.3.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>port</code> <a href="worker_threads.html#class-messageport" class="type">&#x3C;MessagePort></a> | <a href="worker_threads.html#class-broadcastchannel-extends-eventtarget" class="type">&#x3C;BroadcastChannel></a></p>
</li>
<li>
<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></p>
</li>
</ul>
<p>Receive a single message from a given <code>MessagePort</code>. If no message is available,
<code>undefined</code> is returned, otherwise an object with a single <code>message</code> property
that contains the message payload, corresponding to the oldest message in the
<code>MessagePort</code>'s queue.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span>, receiveMessageOnPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port1.<span class="hljs-title function_">postMessage</span>({ <span class="hljs-attr">hello</span>: <span class="hljs-string">'world'</span> });

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">receiveMessageOnPort</span>(port2));
<span class="hljs-comment">// Prints: { message: { hello: 'world' } }</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">receiveMessageOnPort</span>(port2));
<span class="hljs-comment">// Prints: undefined</span></code> <button class="copy-button">copy</button></pre>
<p>When this function is used, no <code>'message'</code> event is emitted and the
<code>onmessage</code> listener is not invoked.</p>
</section><section><h3><code>worker.resourceLimits</code><span><a class="mark" href="#workerresourcelimits" id="workerresourcelimits">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_resourcelimits"></a></h3>
<div class="api_metadata">
<span>Added in: v13.2.0, v12.16.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>maxYoungGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>maxOldGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>codeRangeSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>stackSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
</li>
</ul>
<p>Provides the set of JS engine resource constraints inside this Worker thread.
If the <code>resourceLimits</code> option was passed to the <a href="#class-worker"><code>Worker</code></a> constructor,
this matches its values.</p>
<p>If this is used in the main thread, its value is an empty object.</p>
</section><section><h3><code>worker.SHARE_ENV</code><span><a class="mark" href="#workershare_env" id="workershare_env">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_share_env"></a></h3>
<div class="api_metadata">
<span>Added in: v11.14.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a></li>
</ul>
<p>A special value that can be passed as the <code>env</code> option of the <a href="#class-worker"><code>Worker</code></a>
constructor, to indicate that the current thread and the Worker thread should
share read and write access to the same set of environment variables.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, <span class="hljs-variable constant_">SHARE_ENV</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(<span class="hljs-string">'process.env.SET_IN_WORKER = "foo"'</span>, { <span class="hljs-attr">eval</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">env</span>: <span class="hljs-variable constant_">SHARE_ENV</span> })
  .<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(process.<span class="hljs-property">env</span>.<span class="hljs-property">SET_IN_WORKER</span>);  <span class="hljs-comment">// Prints 'foo'.</span>
  });</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>worker.setEnvironmentData(key[, value])</code><span><a class="mark" href="#workersetenvironmentdatakey-value" id="workersetenvironmentdatakey-value">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_setenvironmentdata_key_value"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v15.12.0, v14.18.0</td>
<td><p><span>Added in: v15.12.0, v14.18.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Any arbitrary, cloneable JavaScript value that can be used as a
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map" class="type">&#x3C;Map></a> key.</li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Any arbitrary, cloneable JavaScript value that will be cloned
and passed automatically to all new <code>Worker</code> instances. If <code>value</code> is passed
as <code>undefined</code>, any previously set value for the <code>key</code> will be deleted.</li>
</ul>
<p>The <code>worker.setEnvironmentData()</code> API sets the content of
<code>worker.getEnvironmentData()</code> in the current thread and all new <code>Worker</code>
instances spawned from the current context.</p>
</section><section><h3><code>worker.threadId</code><span><a class="mark" href="#workerthreadid" id="workerthreadid">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_threadid"></a></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>An integer identifier for the current thread. On the corresponding worker object
(if there is any), it is available as <a href="#workerthreadid_1"><code>worker.threadId</code></a>.
This value is unique for each <a href="#class-worker"><code>Worker</code></a> instance inside a single process.</p>
</section><section><h3><code>worker.workerData</code><span><a class="mark" href="#workerworkerdata" id="workerworkerdata">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_workerdata"></a></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>An arbitrary JavaScript value that contains a clone of the data passed
to this thread's <code>Worker</code> constructor.</p>
<p>The data is cloned as if using <a href="#portpostmessagevalue-transferlist"><code>postMessage()</code></a>,
according to the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, isMainThread, workerData } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename, { <span class="hljs-attr">workerData</span>: <span class="hljs-string">'Hello, world!'</span> });
} <span class="hljs-keyword">else</span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(workerData);  <span class="hljs-comment">// Prints 'Hello, world!'.</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>BroadcastChannel extends EventTarget</code><span><a class="mark" href="#class-broadcastchannel-extends-eventtarget" id="class-broadcastchannel-extends-eventtarget">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_class_broadcastchannel_extends_eventtarget"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v15.4.0</td>
<td><p><span>Added in: v15.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Instances of <code>BroadcastChannel</code> allow asynchronous one-to-many communication
with all other <code>BroadcastChannel</code> instances bound to the same channel name.</p>
<pre><code class="language-js"><span class="hljs-meta">'use strict'</span>;

<span class="hljs-keyword">const</span> {
  isMainThread,
  <span class="hljs-title class_">BroadcastChannel</span>,
  <span class="hljs-title class_">Worker</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">const</span> bc = <span class="hljs-keyword">new</span> <span class="hljs-title class_">BroadcastChannel</span>(<span class="hljs-string">'hello'</span>);

<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-keyword">let</span> c = <span class="hljs-number">0</span>;
  bc.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">event</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">data</span>);
    <span class="hljs-keyword">if</span> (++c === <span class="hljs-number">10</span>) bc.<span class="hljs-title function_">close</span>();
  };
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>; n &#x3C; <span class="hljs-number">10</span>; n++)
    <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
} <span class="hljs-keyword">else</span> {
  bc.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'hello from every worker'</span>);
  bc.<span class="hljs-title function_">close</span>();
}</code> <button class="copy-button">copy</button></pre>
<h4><code>new BroadcastChannel(name)</code><span><a class="mark" href="#new-broadcastchannelname" id="new-broadcastchannelname">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_new_broadcastchannel_name"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The name of the channel to connect to. Any JavaScript value
that can be converted to a string using <code>`${name}`</code> is permitted.</li>
</ul>
<h4><code>broadcastChannel.close()</code><span><a class="mark" href="#broadcastchannelclose" id="broadcastchannelclose">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_close"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<p>Closes the <code>BroadcastChannel</code> connection.</p>
<h4><code>broadcastChannel.onmessage</code><span><a class="mark" href="#broadcastchannelonmessage" id="broadcastchannelonmessage">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_onmessage"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Invoked with a single <code>MessageEvent</code> argument
when a message is received.</li>
</ul>
<h4><code>broadcastChannel.onmessageerror</code><span><a class="mark" href="#broadcastchannelonmessageerror" id="broadcastchannelonmessageerror">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_onmessageerror"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Invoked with a received message cannot be
deserialized.</li>
</ul>
<h4><code>broadcastChannel.postMessage(message)</code><span><a class="mark" href="#broadcastchannelpostmessagemessage" id="broadcastchannelpostmessagemessage">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_postmessage_message"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Any cloneable JavaScript value.</li>
</ul>
<h4><code>broadcastChannel.ref()</code><span><a class="mark" href="#broadcastchannelref" id="broadcastchannelref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_ref"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<p>Opposite of <code>unref()</code>. Calling <code>ref()</code> on a previously <code>unref()</code>ed
BroadcastChannel does <em>not</em> let the program exit if it's the only active handle
left (the default behavior). If the port is <code>ref()</code>ed, calling <code>ref()</code> again
has no effect.</p>
<h4><code>broadcastChannel.unref()</code><span><a class="mark" href="#broadcastchannelunref" id="broadcastchannelunref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<p>Calling <code>unref()</code> on a BroadcastChannel allows the thread to exit if this
is the only active handle in the event system. If the BroadcastChannel is
already <code>unref()</code>ed calling <code>unref()</code> again has no effect.</p>
</section><section><h3>Class: <code>MessageChannel</code><span><a class="mark" href="#class-messagechannel" id="class-messagechannel">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_class_messagechannel"></a></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Instances of the <code>worker.MessageChannel</code> class represent an asynchronous,
two-way communications channel.
The <code>MessageChannel</code> has no methods of its own. <code>new MessageChannel()</code>
yields an object with <code>port1</code> and <code>port2</code> properties, which refer to linked
<a href="#class-messageport"><code>MessagePort</code></a> instances.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'received'</span>, message));
port2.<span class="hljs-title function_">postMessage</span>({ <span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span> });
<span class="hljs-comment">// Prints: received { foo: 'bar' } from the `port1.on('message')` listener</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>MessagePort</code><span><a class="mark" href="#class-messageport" id="class-messageport">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_class_messageport"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.7.0</td>
<td><p>This class now inherits from <code>EventTarget</code> rather than from <code>EventEmitter</code>.</p></td></tr>
<tr><td>v10.5.0</td>
<td><p><span>Added in: v10.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Extends: <a href="events.html#class-eventtarget" class="type">&#x3C;EventTarget></a></li>
</ul>
<p>Instances of the <code>worker.MessagePort</code> class represent one end of an
asynchronous, two-way communications channel. It can be used to transfer
structured data, memory regions and other <code>MessagePort</code>s between different
<a href="#class-worker"><code>Worker</code></a>s.</p>
<p>This implementation matches <a href="https://developer.mozilla.org/en-US/docs/Web/API/MessagePort">browser <code>MessagePort</code></a>s.</p>
<h4>Event: <code>'close'</code><span><a class="mark" href="#event-close" id="event-close">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_close"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>The <code>'close'</code> event is emitted once either side of the channel has been
disconnected.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   foobar</span>
<span class="hljs-comment">//   closed!</span>
port2.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message));
port2.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'closed!'</span>));

port1.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'foobar'</span>);
port1.<span class="hljs-title function_">close</span>();</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'message'</code><span><a class="mark" href="#event-message" id="event-message">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_message"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The transmitted value</li>
</ul>
<p>The <code>'message'</code> event is emitted for any incoming message, containing the cloned
input of <a href="#portpostmessagevalue-transferlist"><code>port.postMessage()</code></a>.</p>
<p>Listeners on this event receive a clone of the <code>value</code> parameter as passed
to <code>postMessage()</code> and no further arguments.</p>
<h4>Event: <code>'messageerror'</code><span><a class="mark" href="#event-messageerror" id="event-messageerror">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_messageerror"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.0</span>
</div>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> An Error object</li>
</ul>
<p>The <code>'messageerror'</code> event is emitted when deserializing a message failed.</p>
<p>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 <code>vm.Context</code> (where Node.js APIs are currently
unavailable).</p>
<h4><code>port.close()</code><span><a class="mark" href="#portclose" id="portclose">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_close"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Disables further sending of messages on either side of the connection.
This method can be called when no further communication will happen over this
<code>MessagePort</code>.</p>
<p>The <a href="#event-close"><code>'close'</code> event</a> is emitted on both <code>MessagePort</code> instances that
are part of the channel.</p>
<h4><code>port.postMessage(value[, transferList])</code><span><a class="mark" href="#portpostmessagevalue-transferlist" id="portpostmessagevalue-transferlist">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_postmessage_value_transferlist"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v21.0.0</td>
<td><p>An error is thrown when an untransferable object is in the transfer list.</p></td></tr>
<tr><td>v15.6.0</td>
<td><p>Added <code>X509Certificate</code> to the list of cloneable types.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>Added <code>CryptoKey</code> to the list of cloneable types.</p></td></tr>
<tr><td>v15.14.0, v14.18.0</td>
<td><p>Add 'BlockList' to the list of cloneable types.</p></td></tr>
<tr><td>v15.9.0, v14.18.0</td>
<td><p>Add 'Histogram' types to the list of cloneable types.</p></td></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>Added <code>KeyObject</code> to the list of cloneable types.</p></td></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>Added <code>FileHandle</code> to the list of transferable types.</p></td></tr>
<tr><td>v10.5.0</td>
<td><p><span>Added in: v10.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a></li>
</ul>
<p>Sends a JavaScript value to the receiving side of this channel.
<code>value</code> is transferred in a way which is compatible with
the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>.</p>
<p>In particular, the significant differences to <code>JSON</code> are:</p>
<ul>
<li><code>value</code> may contain circular references.</li>
<li><code>value</code> may contain instances of builtin JS types such as <code>RegExp</code>s,
<code>BigInt</code>s, <code>Map</code>s, <code>Set</code>s, etc.</li>
<li><code>value</code> may contain typed arrays, both using <code>ArrayBuffer</code>s
and <code>SharedArrayBuffer</code>s.</li>
<li><code>value</code> may contain <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module"><code>WebAssembly.Module</code></a> instances.</li>
<li><code>value</code> may not contain native (C++-backed) objects other than:
<ul>
<li><a href="webcrypto.html#class-cryptokey" class="type">&#x3C;CryptoKey></a>s,</li>
<li><a href="fs.html#class-filehandle" class="type">&#x3C;FileHandle></a>s,</li>
<li><a href="perf_hooks.html#class-histogram" class="type">&#x3C;Histogram></a>s,</li>
<li><a href="crypto.html#class-keyobject" class="type">&#x3C;KeyObject></a>s,</li>
<li><a href="worker_threads.html#class-messageport" class="type">&#x3C;MessagePort></a>s,</li>
<li><a href="net.html#class-netblocklist" class="type">&#x3C;net.BlockList></a>s,</li>
<li><a href="net.html#class-netsocketaddress" class="type">&#x3C;net.SocketAddress></a>es,</li>
<li><a href="crypto.html#class-x509certificate" class="type">&#x3C;X509Certificate></a>s.</li>
</ul>
</li>
</ul>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message));

<span class="hljs-keyword">const</span> circularData = {};
circularData.<span class="hljs-property">foo</span> = circularData;
<span class="hljs-comment">// Prints: { foo: [Circular] }</span>
port2.<span class="hljs-title function_">postMessage</span>(circularData);</code> <button class="copy-button">copy</button></pre>
<p><code>transferList</code> may be a list of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>, <a href="#class-messageport"><code>MessagePort</code></a>, and
<a href="fs.html#class-filehandle"><code>FileHandle</code></a> objects.
After transferring, they are not usable on the sending side of the channel
anymore (even if they are not contained in <code>value</code>). Unlike with
<a href="child_process.html">child processes</a>, transferring handles such as network sockets is currently
not supported.</p>
<p>If <code>value</code> contains <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> instances, those are accessible
from either thread. They cannot be listed in <code>transferList</code>.</p>
<p><code>value</code> may still contain <code>ArrayBuffer</code> instances that are not in
<code>transferList</code>; in that case, the underlying memory is copied rather than moved.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message));

<span class="hljs-keyword">const</span> uint8Array = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>([ <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span> ]);
<span class="hljs-comment">// This posts a copy of `uint8Array`:</span>
port2.<span class="hljs-title function_">postMessage</span>(uint8Array);
<span class="hljs-comment">// This does not copy data, but renders `uint8Array` unusable:</span>
port2.<span class="hljs-title function_">postMessage</span>(uint8Array, [ uint8Array.<span class="hljs-property">buffer</span> ]);

<span class="hljs-comment">// The memory for the `sharedUint8Array` is accessible from both the</span>
<span class="hljs-comment">// original and the copy received by `.on('message')`:</span>
<span class="hljs-keyword">const</span> sharedUint8Array = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">SharedArrayBuffer</span>(<span class="hljs-number">4</span>));
port2.<span class="hljs-title function_">postMessage</span>(sharedUint8Array);

<span class="hljs-comment">// This transfers a freshly created message port to the receiver.</span>
<span class="hljs-comment">// This can be used, for example, to create communication channels between</span>
<span class="hljs-comment">// multiple `Worker` threads that are children of the same parent thread.</span>
<span class="hljs-keyword">const</span> otherChannel = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port2.<span class="hljs-title function_">postMessage</span>({ <span class="hljs-attr">port</span>: otherChannel.<span class="hljs-property">port1</span> }, [ otherChannel.<span class="hljs-property">port1</span> ]);</code> <button class="copy-button">copy</button></pre>
<p>The message object is cloned immediately, and can be modified after
posting without having side effects.</p>
<p>For more information on the serialization and deserialization mechanisms
behind this API, see the <a href="v8.html#serialization-api">serialization API of the <code>node:v8</code> module</a>.</p>
<h5>Considerations when transferring TypedArrays and Buffers<span><a class="mark" href="#considerations-when-transferring-typedarrays-and-buffers" id="considerations-when-transferring-typedarrays-and-buffers">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_considerations_when_transferring_typedarrays_and_buffers"></a></h5>
<p>All <code>TypedArray</code> and <code>Buffer</code> instances are views over an underlying
<code>ArrayBuffer</code>. That is, it is the <code>ArrayBuffer</code> that actually stores
the raw data while the <code>TypedArray</code> and <code>Buffer</code> objects provide a
way of viewing and manipulating the data. It is possible and common
for multiple views to be created over the same <code>ArrayBuffer</code> instance.
Great care must be taken when using a transfer list to transfer an
<code>ArrayBuffer</code> as doing so causes all <code>TypedArray</code> and <code>Buffer</code>
instances that share that same <code>ArrayBuffer</code> to become unusable.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> ab = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>);

<span class="hljs-keyword">const</span> u1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(ab);
<span class="hljs-keyword">const</span> u2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>(ab);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(u2.<span class="hljs-property">length</span>);  <span class="hljs-comment">// prints 5</span>

port.<span class="hljs-title function_">postMessage</span>(u1, [u1.<span class="hljs-property">buffer</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(u2.<span class="hljs-property">length</span>);  <span class="hljs-comment">// prints 0</span></code> <button class="copy-button">copy</button></pre>
<p>For <code>Buffer</code> instances, specifically, whether the underlying
<code>ArrayBuffer</code> can be transferred or cloned depends entirely on how
instances were created, which often cannot be reliably determined.</p>
<p>An <code>ArrayBuffer</code> can be marked with <a href="#workermarkasuntransferableobject"><code>markAsUntransferable()</code></a> to indicate
that it should always be cloned and never transferred.</p>
<p>Depending on how a <code>Buffer</code> instance was created, it may or may
not own its underlying <code>ArrayBuffer</code>. An <code>ArrayBuffer</code> must not
be transferred unless it is known that the <code>Buffer</code> instance
owns it. In particular, for <code>Buffer</code>s created from the internal
<code>Buffer</code> pool (using, for instance <code>Buffer.from()</code> or <code>Buffer.allocUnsafe()</code>),
transferring them is not possible and they are always cloned,
which sends a copy of the entire <code>Buffer</code> pool.
This behavior may come with unintended higher memory
usage and possible security concerns.</p>
<p>See <a href="buffer.html#static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a> for more details on <code>Buffer</code> pooling.</p>
<p>The <code>ArrayBuffer</code>s for <code>Buffer</code> instances created using
<code>Buffer.alloc()</code> or <code>Buffer.allocUnsafeSlow()</code> can always be
transferred but doing so renders all other existing views of
those <code>ArrayBuffer</code>s unusable.</p>
<h5>Considerations when cloning objects with prototypes, classes, and accessors<span><a class="mark" href="#considerations-when-cloning-objects-with-prototypes-classes-and-accessors" id="considerations-when-cloning-objects-with-prototypes-classes-and-accessors">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_considerations_when_cloning_objects_with_prototypes_classes_and_accessors"></a></h5>
<p>Because object cloning uses the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>,
non-enumerable properties, property accessors, and object prototypes are
not preserved. In particular, <a href="buffer.html"><code>Buffer</code></a> objects will be read as
plain <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a>s on the receiving side, and instances of JavaScript
classes will be cloned as plain JavaScript objects.</p>
<!-- eslint-disable no-unused-private-class-members -->
<pre><code class="language-js"><span class="hljs-keyword">const</span> b = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'b'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Foo</span> {
  #a = <span class="hljs-number">1</span>;
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params"></span>) {
    <span class="hljs-variable language_">this</span>[b] = <span class="hljs-number">2</span>;
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">c</span> = <span class="hljs-number">3</span>;
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title function_">d</span>() { <span class="hljs-keyword">return</span> <span class="hljs-number">4</span>; }
}

<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

port1.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">{ data }</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);

port2.<span class="hljs-title function_">postMessage</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Foo</span>());

<span class="hljs-comment">// Prints: { c: 3 }</span></code> <button class="copy-button">copy</button></pre>
<p>This limitation extends to many built-in objects, such as the global <code>URL</code>
object:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

port1.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">{ data }</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);

port2.<span class="hljs-title function_">postMessage</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org'</span>));

<span class="hljs-comment">// Prints: { }</span></code> <button class="copy-button">copy</button></pre>
<h4><code>port.hasRef()</code><span><a class="mark" href="#porthasref" id="porthasref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_hasref"></a></h4>
<div class="api_metadata">
<span>Added in: v18.1.0, v16.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>If true, the <code>MessagePort</code> object will keep the Node.js event loop active.</p>
<h4><code>port.ref()</code><span><a class="mark" href="#portref" id="portref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_ref"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Opposite of <code>unref()</code>. Calling <code>ref()</code> on a previously <code>unref()</code>ed port does
<em>not</em> let the program exit if it's the only active handle left (the default
behavior). If the port is <code>ref()</code>ed, calling <code>ref()</code> again has no effect.</p>
<p>If listeners are attached or removed using <code>.on('message')</code>, the port
is <code>ref()</code>ed and <code>unref()</code>ed automatically depending on whether
listeners for the event exist.</p>
<h4><code>port.start()</code><span><a class="mark" href="#portstart" id="portstart">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_start"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Starts receiving messages on this <code>MessagePort</code>. When using this port
as an event emitter, this is called automatically once <code>'message'</code>
listeners are attached.</p>
<p>This method exists for parity with the Web <code>MessagePort</code> API. In Node.js,
it is only useful for ignoring messages when no event listener is present.
Node.js also diverges in its handling of <code>.onmessage</code>. Setting it
automatically calls <code>.start()</code>, but unsetting it lets messages queue up
until a new handler is set or the port is discarded.</p>
<h4><code>port.unref()</code><span><a class="mark" href="#portunref" id="portunref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Calling <code>unref()</code> on a port allows the thread to exit if this is the only
active handle in the event system. If the port is already <code>unref()</code>ed calling
<code>unref()</code> again has no effect.</p>
<p>If listeners are attached or removed using <code>.on('message')</code>, the port is
<code>ref()</code>ed and <code>unref()</code>ed automatically depending on whether
listeners for the event exist.</p>
</section><section><h3>Class: <code>Worker</code><span><a class="mark" href="#class-worker" id="class-worker">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_class_worker"></a></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li>Extends: <a href="events.html#class-eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>The <code>Worker</code> class represents an independent JavaScript execution thread.
Most Node.js APIs are available inside of it.</p>
<p>Notable differences inside a Worker environment are:</p>
<ul>
<li>The <a href="process.html#processstdin"><code>process.stdin</code></a>, <a href="process.html#processstdout"><code>process.stdout</code></a>, and <a href="process.html#processstderr"><code>process.stderr</code></a>
streams may be redirected by the parent thread.</li>
<li>The <a href="#workerismainthread"><code>require('node:worker_threads').isMainThread</code></a> property is set to <code>false</code>.</li>
<li>The <a href="#workerparentport"><code>require('node:worker_threads').parentPort</code></a> message port is available.</li>
<li><a href="process.html#processexitcode"><code>process.exit()</code></a> does not stop the whole program, just the single thread,
and <a href="process.html#processabort"><code>process.abort()</code></a> is not available.</li>
<li><a href="process.html#processchdirdirectory"><code>process.chdir()</code></a> and <code>process</code> methods that set group or user ids
are not available.</li>
<li><a href="process.html#processenv"><code>process.env</code></a> 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
<a href="#workershare_env"><code>worker.SHARE_ENV</code></a> is passed as the <code>env</code> option to the
<a href="#class-worker"><code>Worker</code></a> constructor). On Windows, unlike the main thread, a copy of the
environment variables operates in a case-sensitive manner.</li>
<li><a href="process.html#processtitle"><code>process.title</code></a> cannot be modified.</li>
<li>Signals are not delivered through <a href="process.html#signal-events"><code>process.on('...')</code></a>.</li>
<li>Execution may stop at any point as a result of <a href="#workerterminate"><code>worker.terminate()</code></a>
being invoked.</li>
<li>IPC channels from parent processes are not accessible.</li>
<li>The <a href="tracing.html"><code>trace_events</code></a> module is not supported.</li>
<li>Native add-ons can only be loaded from multiple threads if they fulfill
<a href="addons.html#worker-support">certain conditions</a>.</li>
</ul>
<p>Creating <code>Worker</code> instances inside of other <code>Worker</code>s is possible.</p>
<p>Like <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">Web Workers</a> and the <a href="cluster.html"><code>node:cluster</code> module</a>, two-way communication
can be achieved through inter-thread message passing. Internally, a <code>Worker</code> has
a built-in pair of <a href="#class-messageport"><code>MessagePort</code></a>s that are already associated with each
other when the <code>Worker</code> is created. While the <code>MessagePort</code> object on the parent
side is not directly exposed, its functionalities are exposed through
<a href="#workerpostmessagevalue-transferlist"><code>worker.postMessage()</code></a> and the <a href="#event-message_1"><code>worker.on('message')</code></a> event
on the <code>Worker</code> object for the parent thread.</p>
<p>To create custom messaging channels (which is encouraged over using the default
global channel because it facilitates separation of concerns), users can create
a <code>MessageChannel</code> object on either thread and pass one of the
<code>MessagePort</code>s on that <code>MessageChannel</code> to the other thread through a
pre-existing channel, such as the global one.</p>
<p>See <a href="#portpostmessagevalue-transferlist"><code>port.postMessage()</code></a> for more information on how messages are passed,
and what kind of JavaScript values can be successfully transported through
the thread barrier.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> {
  <span class="hljs-title class_">Worker</span>, <span class="hljs-title class_">MessageChannel</span>, <span class="hljs-title class_">MessagePort</span>, isMainThread, parentPort,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
  <span class="hljs-keyword">const</span> subChannel = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
  worker.<span class="hljs-title function_">postMessage</span>({ <span class="hljs-attr">hereIsYourPort</span>: subChannel.<span class="hljs-property">port1</span> }, [subChannel.<span class="hljs-property">port1</span>]);
  subChannel.<span class="hljs-property">port2</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">value</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'received:'</span>, value);
  });
} <span class="hljs-keyword">else</span> {
  parentPort.<span class="hljs-title function_">once</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">value</span>) =></span> {
    <span class="hljs-title function_">assert</span>(value.<span class="hljs-property">hereIsYourPort</span> <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">MessagePort</span>);
    value.<span class="hljs-property">hereIsYourPort</span>.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'the worker is sending this'</span>);
    value.<span class="hljs-property">hereIsYourPort</span>.<span class="hljs-title function_">close</span>();
  });
}</code> <button class="copy-button">copy</button></pre>
<h4><code>new Worker(filename[, options])</code><span><a class="mark" href="#new-workerfilename-options" id="new-workerfilename-options">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_new_worker_filename_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.8.0, v18.16.0</td>
<td><p>Added support for a <code>name</code> option, which allows adding a name to worker title for debugging.</p></td></tr>
<tr><td>v14.9.0</td>
<td><p>The <code>filename</code> parameter can be a WHATWG <code>URL</code> object using <code>data:</code> protocol.</p></td></tr>
<tr><td>v14.9.0</td>
<td><p>The <code>trackUnmanagedFds</code> option was set to <code>true</code> by default.</p></td></tr>
<tr><td>v14.6.0, v12.19.0</td>
<td><p>The <code>trackUnmanagedFds</code> option was introduced.</p></td></tr>
<tr><td>v13.13.0, v12.17.0</td>
<td><p>The <code>transferList</code> option was introduced.</p></td></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>The <code>filename</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v13.4.0, v12.16.0</td>
<td><p>The <code>argv</code> option was introduced.</p></td></tr>
<tr><td>v13.2.0, v12.16.0</td>
<td><p>The <code>resourceLimits</code> option was introduced.</p></td></tr>
<tr><td>v10.5.0</td>
<td><p><span>Added in: v10.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="url.html#the-whatwg-url-api" class="type">&#x3C;URL></a> The path to the Worker's main script or module. Must
be either an absolute path or a relative path (i.e. relative to the
current working directory) starting with <code>./</code> or <code>../</code>, or a WHATWG <code>URL</code>
object using <code>file:</code> or <code>data:</code> protocol.
When using a <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs"><code>data:</code> URL</a>, the data is interpreted based on MIME type using
the <a href="esm.html#data-imports">ECMAScript module loader</a>.
If <code>options.eval</code> is <code>true</code>, this is a string containing JavaScript code
rather than a path.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>argv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any[]></a> List of arguments which would be stringified and appended to
<code>process.argv</code> in the worker. This is mostly similar to the <code>workerData</code>
but the values are available on the global <code>process.argv</code> as if they
were passed as CLI options to the script.</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> If set, specifies the initial value of <code>process.env</code> inside
the Worker thread. As a special value, <a href="#workershare_env"><code>worker.SHARE_ENV</code></a> may be used
to specify that the parent thread and the child thread should share their
environment variables; in that case, changes to one thread's <code>process.env</code>
object affect the other thread as well. <strong>Default:</strong> <code>process.env</code>.</li>
<li><code>eval</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code> and the first argument is a <code>string</code>, interpret
the first argument to the constructor as a script that is executed once the
worker is online.</li>
<li><code>execArgv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> List of node CLI options passed to the worker.
V8 options (such as <code>--max-old-space-size</code>) and options that affect the
process (such as <code>--title</code>) are not supported. If set, this is provided
as <a href="process.html#processexecargv"><code>process.execArgv</code></a> inside the worker. By default, options are
inherited from the parent thread.</li>
<li><code>stdin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If this is set to <code>true</code>, then <code>worker.stdin</code>
provides a writable stream whose contents appear as <code>process.stdin</code>
inside the Worker. By default, no data is provided.</li>
<li><code>stdout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If this is set to <code>true</code>, then <code>worker.stdout</code> is
not automatically piped through to <code>process.stdout</code> in the parent.</li>
<li><code>stderr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If this is set to <code>true</code>, then <code>worker.stderr</code> is
not automatically piped through to <code>process.stderr</code> in the parent.</li>
<li><code>workerData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Any JavaScript value that is cloned and made
available as <a href="#workerworkerdata"><code>require('node:worker_threads').workerData</code></a>. The cloning
occurs as described in the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>, and an error
is thrown if the object cannot be cloned (e.g. because it contains
<code>function</code>s).</li>
<li><code>trackUnmanagedFds</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If this is set to <code>true</code>, then the Worker
tracks raw file descriptors managed through <a href="fs.html#fsopenpath-flags-mode-callback"><code>fs.open()</code></a> and
<a href="fs.html#fsclosefd-callback"><code>fs.close()</code></a>, and closes them when the Worker exits, similar to other
resources like network sockets or file descriptors managed through
the <a href="fs.html#class-filehandle"><code>FileHandle</code></a> API. This option is automatically inherited by all
nested <code>Worker</code>s. <strong>Default:</strong> <code>true</code>.</li>
<li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a> If one or more <code>MessagePort</code>-like objects
are passed in <code>workerData</code>, a <code>transferList</code> is required for those
items or <a href="errors.html#err_missing_message_port_in_transfer_list"><code>ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST</code></a> is thrown.
See <a href="#portpostmessagevalue-transferlist"><code>port.postMessage()</code></a> for more information.</li>
<li><code>resourceLimits</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> An optional set of resource limits for the new JS
engine instance. Reaching these limits leads to termination of the <code>Worker</code>
instance. These limits only affect the JS engine, and no external data,
including no <code>ArrayBuffer</code>s. Even if these limits are set, the process may
still abort if it encounters a global out-of-memory situation.
<ul>
<li><code>maxOldGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The maximum size of the main heap in
MB. If the command-line argument <a href="cli.html#--max-old-space-sizesize-in-mib"><code>--max-old-space-size</code></a> is set, it
overrides this setting.</li>
<li><code>maxYoungGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The maximum size of a heap space for
recently created objects. If the command-line argument
<a href="cli.html#--max-semi-space-sizesize-in-mib"><code>--max-semi-space-size</code></a> is set, it overrides this setting.</li>
<li><code>codeRangeSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The size of a pre-allocated memory range
used for generated code.</li>
<li><code>stackSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The default maximum stack size for the thread.
Small values may lead to unusable Worker instances. <strong>Default:</strong> <code>4</code>.</li>
</ul>
</li>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> An optional <code>name</code> to be appended to the worker title
for debugging/identification purposes, making the final title as
<code>[worker ${id}] ${name}</code>. <strong>Default:</strong> <code>''</code>.</li>
</ul>
</li>
</ul>
<h4>Event: <code>'error'</code><span><a class="mark" href="#event-error" id="event-error">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_error"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
<p>The <code>'error'</code> event is emitted if the worker thread throws an uncaught
exception. In that case, the worker is terminated.</p>
<h4>Event: <code>'exit'</code><span><a class="mark" href="#event-exit" id="event-exit">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_exit"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><code>exitCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>The <code>'exit'</code> event is emitted once the worker has stopped. If the worker
exited by calling <a href="process.html#processexitcode"><code>process.exit()</code></a>, the <code>exitCode</code> parameter is the
passed exit code. If the worker was terminated, the <code>exitCode</code> parameter is
<code>1</code>.</p>
<p>This is the final event emitted by any <code>Worker</code> instance.</p>
<h4>Event: <code>'message'</code><span><a class="mark" href="#event-message_1" id="event-message_1">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_message_1"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The transmitted value</li>
</ul>
<p>The <code>'message'</code> event is emitted when the worker thread has invoked
<a href="#workerpostmessagevalue-transferlist"><code>require('node:worker_threads').parentPort.postMessage()</code></a>.
See the <a href="#event-message"><code>port.on('message')</code></a> event for more details.</p>
<p>All messages sent from the worker thread are emitted before the
<a href="#event-exit"><code>'exit'</code> event</a> is emitted on the <code>Worker</code> object.</p>
<h4>Event: <code>'messageerror'</code><span><a class="mark" href="#event-messageerror_1" id="event-messageerror_1">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_messageerror_1"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.0</span>
</div>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> An Error object</li>
</ul>
<p>The <code>'messageerror'</code> event is emitted when deserializing a message failed.</p>
<h4>Event: <code>'online'</code><span><a class="mark" href="#event-online" id="event-online">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_online"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>The <code>'online'</code> event is emitted when the worker thread has started executing
JavaScript code.</p>
<h4><code>worker.getHeapSnapshot([options])</code><span><a class="mark" href="#workergetheapsnapshotoptions" id="workergetheapsnapshotoptions">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_getheapsnapshot_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.1.0</td>
<td><p>Support options to configure the heap snapshot.</p></td></tr>
<tr><td>v13.9.0, v12.17.0</td>
<td><p><span>Added in: v13.9.0, v12.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>exposeInternals</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If true, expose internals in the heap snapshot.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>exposeNumericValues</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If true, expose numeric values in
artificial fields. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> A promise for a Readable Stream containing
a V8 heap snapshot</li>
</ul>
<p>Returns a readable stream for a V8 snapshot of the current state of the Worker.
See <a href="v8.html#v8getheapsnapshotoptions"><code>v8.getHeapSnapshot()</code></a> for more details.</p>
<p>If the Worker thread is no longer running, which may occur before the
<a href="#event-exit"><code>'exit'</code> event</a> is emitted, the returned <code>Promise</code> is rejected
immediately with an <a href="errors.html#err_worker_not_running"><code>ERR_WORKER_NOT_RUNNING</code></a> error.</p>
<h4><code>worker.performance</code><span><a class="mark" href="#workerperformance" id="workerperformance">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_performance"></a></h4>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0, v12.22.0</span>
</div>
<p>An object that can be used to query performance information from a worker
instance. Similar to <a href="perf_hooks.html#perf_hooksperformance"><code>perf_hooks.performance</code></a>.</p>
<h5><code>performance.eventLoopUtilization([utilization1[, utilization2]])</code><span><a class="mark" href="#performanceeventlooputilizationutilization1-utilization2" id="performanceeventlooputilizationutilization1-utilization2">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_performance_eventlooputilization_utilization1_utilization2"></a></h5>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0, v12.22.0</span>
</div>
<ul>
<li><code>utilization1</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The result of a previous call to
<code>eventLoopUtilization()</code>.</li>
<li><code>utilization2</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The result of a previous call to
<code>eventLoopUtilization()</code> prior to <code>utilization1</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>idle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>active</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>utilization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
</li>
</ul>
<p>The same call as <a href="perf_hooks.html#performanceeventlooputilizationutilization1-utilization2"><code>perf_hooks</code> <code>eventLoopUtilization()</code></a>, except the values
of the worker instance are returned.</p>
<p>One difference is that, unlike the main thread, bootstrapping within a worker
is done within the event loop. So the event loop utilization is
immediately available once the worker's script begins execution.</p>
<p>An <code>idle</code> time that does not increase does not indicate that the worker is
stuck in bootstrap. The following examples shows how the worker's entire
lifetime never accumulates any <code>idle</code> time, but is still be able to process
messages.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, isMainThread, parentPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
  <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> {
    worker.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'hi'</span>);
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(worker.<span class="hljs-property">performance</span>.<span class="hljs-title function_">eventLoopUtilization</span>());
  }, <span class="hljs-number">100</span>).<span class="hljs-title function_">unref</span>();
  <span class="hljs-keyword">return</span>;
}

parentPort.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'msg'</span>)).<span class="hljs-title function_">unref</span>();
(<span class="hljs-keyword">function</span> <span class="hljs-title function_">r</span>(<span class="hljs-params">n</span>) {
  <span class="hljs-keyword">if</span> (--n &#x3C; <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span>;
  <span class="hljs-keyword">const</span> t = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>();
  <span class="hljs-keyword">while</span> (<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>() - t &#x3C; <span class="hljs-number">300</span>);
  <span class="hljs-title function_">setImmediate</span>(r, n);
})(<span class="hljs-number">10</span>);</code> <button class="copy-button">copy</button></pre>
<p>The event loop utilization of a worker is available only after the <a href="#event-online"><code>'online'</code>
event</a> emitted, and if called before this, or after the <a href="#event-exit"><code>'exit'</code>
event</a>, then all properties have the value of <code>0</code>.</p>
<h4><code>worker.postMessage(value[, transferList])</code><span><a class="mark" href="#workerpostmessagevalue-transferlist" id="workerpostmessagevalue-transferlist">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_postmessage_value_transferlist"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a></li>
</ul>
<p>Send a message to the worker that is received via
<a href="#event-message"><code>require('node:worker_threads').parentPort.on('message')</code></a>.
See <a href="#portpostmessagevalue-transferlist"><code>port.postMessage()</code></a> for more details.</p>
<h4><code>worker.ref()</code><span><a class="mark" href="#workerref" id="workerref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_ref"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Opposite of <code>unref()</code>, calling <code>ref()</code> on a previously <code>unref()</code>ed worker does
<em>not</em> let the program exit if it's the only active handle left (the default
behavior). If the worker is <code>ref()</code>ed, calling <code>ref()</code> again has
no effect.</p>
<h4><code>worker.resourceLimits</code><span><a class="mark" href="#workerresourcelimits_1" id="workerresourcelimits_1">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_resourcelimits_1"></a></h4>
<div class="api_metadata">
<span>Added in: v13.2.0, v12.16.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>maxYoungGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>maxOldGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>codeRangeSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>stackSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
</li>
</ul>
<p>Provides the set of JS engine resource constraints for this Worker thread.
If the <code>resourceLimits</code> option was passed to the <a href="#class-worker"><code>Worker</code></a> constructor,
this matches its values.</p>
<p>If the worker has stopped, the return value is an empty object.</p>
<h4><code>worker.stderr</code><span><a class="mark" href="#workerstderr" id="workerstderr">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_stderr"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><a href="stream.html#class-streamreadable" class="type">&#x3C;stream.Readable></a></li>
</ul>
<p>This is a readable stream which contains data written to <a href="process.html#processstderr"><code>process.stderr</code></a>
inside the worker thread. If <code>stderr: true</code> was not passed to the
<a href="#class-worker"><code>Worker</code></a> constructor, then data is piped to the parent thread's
<a href="process.html#processstderr"><code>process.stderr</code></a> stream.</p>
<h4><code>worker.stdin</code><span><a class="mark" href="#workerstdin" id="workerstdin">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_stdin"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> | <a href="stream.html#class-streamwritable" class="type">&#x3C;stream.Writable></a></li>
</ul>
<p>If <code>stdin: true</code> was passed to the <a href="#class-worker"><code>Worker</code></a> constructor, this is a
writable stream. The data written to this stream will be made available in
the worker thread as <a href="process.html#processstdin"><code>process.stdin</code></a>.</p>
<h4><code>worker.stdout</code><span><a class="mark" href="#workerstdout" id="workerstdout">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_stdout"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><a href="stream.html#class-streamreadable" class="type">&#x3C;stream.Readable></a></li>
</ul>
<p>This is a readable stream which contains data written to <a href="process.html#processstdout"><code>process.stdout</code></a>
inside the worker thread. If <code>stdout: true</code> was not passed to the
<a href="#class-worker"><code>Worker</code></a> constructor, then data is piped to the parent thread's
<a href="process.html#processstdout"><code>process.stdout</code></a> stream.</p>
<h4><code>worker.terminate()</code><span><a class="mark" href="#workerterminate" id="workerterminate">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_terminate"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.5.0</td>
<td><p>This function now returns a Promise. Passing a callback is deprecated, and was useless up to this version, as the Worker was actually terminated synchronously. Terminating is now a fully asynchronous operation.</p></td></tr>
<tr><td>v10.5.0</td>
<td><p><span>Added in: v10.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Stop all JavaScript execution in the worker thread as soon as possible.
Returns a Promise for the exit code that is fulfilled when the
<a href="#event-exit"><code>'exit'</code> event</a> is emitted.</p>
<h4><code>worker.threadId</code><span><a class="mark" href="#workerthreadid_1" id="workerthreadid_1">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_threadid_1"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>An integer identifier for the referenced thread. Inside the worker thread,
it is available as <a href="#workerthreadid"><code>require('node:worker_threads').threadId</code></a>.
This value is unique for each <code>Worker</code> instance inside a single process.</p>
<h4><code>worker.unref()</code><span><a class="mark" href="#workerunref" id="workerunref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Calling <code>unref()</code> on a worker allows the thread to exit if this is the only
active handle in the event system. If the worker is already <code>unref()</code>ed calling
<code>unref()</code> again has no effect.</p>
</section><section><h3>Notes<span><a class="mark" href="#notes" id="notes">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_notes"></a></h3>
<h4>Synchronous blocking of stdio<span><a class="mark" href="#synchronous-blocking-of-stdio" id="synchronous-blocking-of-stdio">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_synchronous_blocking_of_stdio"></a></h4>
<p><code>Worker</code>s utilize message passing via <a href="worker_threads.html#class-messageport" class="type">&#x3C;MessagePort></a> to implement interactions
with <code>stdio</code>. This means that <code>stdio</code> output originating from a <code>Worker</code> can
get blocked by synchronous code on the receiving end that is blocking the
Node.js event loop.</p>

<pre class="with-13-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> {
  <span class="hljs-title class_">Worker</span>,
  isMainThread,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;

<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>));
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>; n &#x3C; <span class="hljs-number">1e10</span>; n++) {
    <span class="hljs-comment">// Looping to simulate work.</span>
  }
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// This output will be blocked by the for loop in the main thread.</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo'</span>);
}</code><code class="language-js cjs"><span class="hljs-meta">'use strict'</span>;

<span class="hljs-keyword">const</span> {
  <span class="hljs-title class_">Worker</span>,
  isMainThread,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>; n &#x3C; <span class="hljs-number">1e10</span>; n++) {
    <span class="hljs-comment">// Looping to simulate work.</span>
  }
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// This output will be blocked by the for loop in the main thread.</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo'</span>);
}</code><button class="copy-button">copy</button></pre>
<h4>Launching worker threads from preload scripts<span><a class="mark" href="#launching-worker-threads-from-preload-scripts" id="launching-worker-threads-from-preload-scripts">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_launching_worker_threads_from_preload_scripts"></a></h4>
<p>Take care when launching worker threads from preload scripts (scripts loaded
and run using the <code>-r</code> command line flag). Unless the <code>execArgv</code> option is
explicitly set, new Worker threads automatically inherit the command line flags
from the running process and will preload the same preload scripts as the main
thread. If the preload script unconditionally launches a worker thread, every
thread spawned will spawn another until the application crashes.</p></section>
        <!-- API END -->
      </div>
    </div>
  </div>
</body>
</html>