File: vm.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 (2141 lines) | stat: -rw-r--r-- 177,429 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
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
<!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>VM (executing JavaScript) | 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/vm.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:462px){.with-30-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:702px){.with-60-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:614px){.with-49-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:686px){.with-58-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}</style>
</head>
<body class="alt apidoc" id="api-section-vm">
  <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 active">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">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="vm" 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="#vm-executing-javascript">VM (executing JavaScript)</a></span>
<ul>
<li><a href="#class-vmscript">Class: <code>vm.Script</code></a>
<ul>
<li><a href="#new-vmscriptcode-options"><code>new vm.Script(code[, options])</code></a></li>
<li><a href="#scriptcacheddatarejected"><code>script.cachedDataRejected</code></a></li>
<li><a href="#scriptcreatecacheddata"><code>script.createCachedData()</code></a></li>
<li><a href="#scriptrunincontextcontextifiedobject-options"><code>script.runInContext(contextifiedObject[, options])</code></a></li>
<li><a href="#scriptruninnewcontextcontextobject-options"><code>script.runInNewContext([contextObject[, options]])</code></a></li>
<li><a href="#scriptruninthiscontextoptions"><code>script.runInThisContext([options])</code></a></li>
<li><a href="#scriptsourcemapurl"><code>script.sourceMapURL</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#class-vmmodule">Class: <code>vm.Module</code></a></span>
<ul>
<li><a href="#moduledependencyspecifiers"><code>module.dependencySpecifiers</code></a></li>
<li><a href="#moduleerror"><code>module.error</code></a></li>
<li><a href="#moduleevaluateoptions"><code>module.evaluate([options])</code></a></li>
<li><a href="#moduleidentifier"><code>module.identifier</code></a></li>
<li><a href="#modulelinklinker"><code>module.link(linker)</code></a></li>
<li><a href="#modulenamespace"><code>module.namespace</code></a></li>
<li><a href="#modulestatus"><code>module.status</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#class-vmsourcetextmodule">Class: <code>vm.SourceTextModule</code></a></span>
<ul>
<li><a href="#new-vmsourcetextmodulecode-options"><code>new vm.SourceTextModule(code[, options])</code></a></li>
<li><a href="#sourcetextmodulecreatecacheddata"><code>sourceTextModule.createCachedData()</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#class-vmsyntheticmodule">Class: <code>vm.SyntheticModule</code></a></span>
<ul>
<li><a href="#new-vmsyntheticmoduleexportnames-evaluatecallback-options"><code>new vm.SyntheticModule(exportNames, evaluateCallback[, options])</code></a></li>
<li><a href="#syntheticmodulesetexportname-value"><code>syntheticModule.setExport(name, value)</code></a></li>
</ul>
</li>
<li><a href="#vmcompilefunctioncode-params-options"><code>vm.compileFunction(code[, params[, options]])</code></a></li>
<li><a href="#vmconstants"><code>vm.constants</code></a>
<ul>
<li><span class="stability_1"><a href="#vmconstantsuse_main_context_default_loader"><code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code></a></span></li>
</ul>
</li>
<li><a href="#vmcreatecontextcontextobject-options"><code>vm.createContext([contextObject[, options]])</code></a></li>
<li><a href="#vmiscontextobject"><code>vm.isContext(object)</code></a></li>
<li><span class="stability_1"><a href="#vmmeasurememoryoptions"><code>vm.measureMemory([options])</code></a></span></li>
<li><a href="#vmrunincontextcode-contextifiedobject-options"><code>vm.runInContext(code, contextifiedObject[, options])</code></a></li>
<li><a href="#vmruninnewcontextcode-contextobject-options"><code>vm.runInNewContext(code[, contextObject[, options]])</code></a></li>
<li><a href="#vmruninthiscontextcode-options"><code>vm.runInThisContext(code[, options])</code></a></li>
<li><a href="#example-running-an-http-server-within-a-vm">Example: Running an HTTP server within a VM</a></li>
<li><a href="#what-does-it-mean-to-contextify-an-object">What does it mean to "contextify" an object?</a>
<ul>
<li><a href="#vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a></li>
</ul>
</li>
<li><a href="#timeout-interactions-with-asynchronous-tasks-and-promises">Timeout interactions with asynchronous tasks and Promises</a></li>
<li><a href="#support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>
<ul>
<li><a href="#when-the-importmoduledynamically-option-is-not-specified-or-undefined">When the <code>importModuleDynamically</code> option is not specified or undefined</a></li>
<li><a href="#when-importmoduledynamically-is-vmconstantsuse_main_context_default_loader">When <code>importModuleDynamically</code> is <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code></a></li>
<li><a href="#when-importmoduledynamically-is-a-function">When <code>importModuleDynamically</code> is a function</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 active">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">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/vm.html">23.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v22.x/api/vm.html">22.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v21.x/api/vm.html">21.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v20.x/api/vm.html">20.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v19.x/api/vm.html">19.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v18.x/api/vm.html">18.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v17.x/api/vm.html">17.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v16.x/api/vm.html">16.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v15.x/api/vm.html">15.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v14.x/api/vm.html">14.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v13.x/api/vm.html">13.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v12.x/api/vm.html">12.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v11.x/api/vm.html">11.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v10.x/api/vm.html">10.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v9.x/api/vm.html">9.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v8.x/api/vm.html">8.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v7.x/api/vm.html">7.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v6.x/api/vm.html">6.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v5.x/api/vm.html">5.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v4.x/api/vm.html">4.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v0.12.x/api/vm.html">0.12.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v0.10.x/api/vm.html">0.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="vm.json">View as JSON</a>
                  </li>
                  <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/main/doc/api/vm.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="#vm-executing-javascript">VM (executing JavaScript)</a></span>
<ul>
<li><a href="#class-vmscript">Class: <code>vm.Script</code></a>
<ul>
<li><a href="#new-vmscriptcode-options"><code>new vm.Script(code[, options])</code></a></li>
<li><a href="#scriptcacheddatarejected"><code>script.cachedDataRejected</code></a></li>
<li><a href="#scriptcreatecacheddata"><code>script.createCachedData()</code></a></li>
<li><a href="#scriptrunincontextcontextifiedobject-options"><code>script.runInContext(contextifiedObject[, options])</code></a></li>
<li><a href="#scriptruninnewcontextcontextobject-options"><code>script.runInNewContext([contextObject[, options]])</code></a></li>
<li><a href="#scriptruninthiscontextoptions"><code>script.runInThisContext([options])</code></a></li>
<li><a href="#scriptsourcemapurl"><code>script.sourceMapURL</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#class-vmmodule">Class: <code>vm.Module</code></a></span>
<ul>
<li><a href="#moduledependencyspecifiers"><code>module.dependencySpecifiers</code></a></li>
<li><a href="#moduleerror"><code>module.error</code></a></li>
<li><a href="#moduleevaluateoptions"><code>module.evaluate([options])</code></a></li>
<li><a href="#moduleidentifier"><code>module.identifier</code></a></li>
<li><a href="#modulelinklinker"><code>module.link(linker)</code></a></li>
<li><a href="#modulenamespace"><code>module.namespace</code></a></li>
<li><a href="#modulestatus"><code>module.status</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#class-vmsourcetextmodule">Class: <code>vm.SourceTextModule</code></a></span>
<ul>
<li><a href="#new-vmsourcetextmodulecode-options"><code>new vm.SourceTextModule(code[, options])</code></a></li>
<li><a href="#sourcetextmodulecreatecacheddata"><code>sourceTextModule.createCachedData()</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#class-vmsyntheticmodule">Class: <code>vm.SyntheticModule</code></a></span>
<ul>
<li><a href="#new-vmsyntheticmoduleexportnames-evaluatecallback-options"><code>new vm.SyntheticModule(exportNames, evaluateCallback[, options])</code></a></li>
<li><a href="#syntheticmodulesetexportname-value"><code>syntheticModule.setExport(name, value)</code></a></li>
</ul>
</li>
<li><a href="#vmcompilefunctioncode-params-options"><code>vm.compileFunction(code[, params[, options]])</code></a></li>
<li><a href="#vmconstants"><code>vm.constants</code></a>
<ul>
<li><span class="stability_1"><a href="#vmconstantsuse_main_context_default_loader"><code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code></a></span></li>
</ul>
</li>
<li><a href="#vmcreatecontextcontextobject-options"><code>vm.createContext([contextObject[, options]])</code></a></li>
<li><a href="#vmiscontextobject"><code>vm.isContext(object)</code></a></li>
<li><span class="stability_1"><a href="#vmmeasurememoryoptions"><code>vm.measureMemory([options])</code></a></span></li>
<li><a href="#vmrunincontextcode-contextifiedobject-options"><code>vm.runInContext(code, contextifiedObject[, options])</code></a></li>
<li><a href="#vmruninnewcontextcode-contextobject-options"><code>vm.runInNewContext(code[, contextObject[, options]])</code></a></li>
<li><a href="#vmruninthiscontextcode-options"><code>vm.runInThisContext(code[, options])</code></a></li>
<li><a href="#example-running-an-http-server-within-a-vm">Example: Running an HTTP server within a VM</a></li>
<li><a href="#what-does-it-mean-to-contextify-an-object">What does it mean to "contextify" an object?</a>
<ul>
<li><a href="#vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a></li>
</ul>
</li>
<li><a href="#timeout-interactions-with-asynchronous-tasks-and-promises">Timeout interactions with asynchronous tasks and Promises</a></li>
<li><a href="#support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>
<ul>
<li><a href="#when-the-importmoduledynamically-option-is-not-specified-or-undefined">When the <code>importModuleDynamically</code> option is not specified or undefined</a></li>
<li><a href="#when-importmoduledynamically-is-vmconstantsuse_main_context_default_loader">When <code>importModuleDynamically</code> is <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code></a></li>
<li><a href="#when-importmoduledynamically-is-a-function">When <code>importModuleDynamically</code> is a function</a></li>
</ul>
</li>
</ul>
</li>
</ul></details>

      <div role="main" id="apicontent">
        <h2>VM (executing JavaScript)<span><a class="mark" href="#vm-executing-javascript" id="vm-executing-javascript">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_executing_javascript"></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/vm.js">lib/vm.js</a></p>
<p>The <code>node:vm</code> module enables compiling and running code within V8 Virtual
Machine contexts.</p>
<p><strong class="critical">The <code>node:vm</code> module is not a security
mechanism. Do not use it to run untrusted code.</strong></p>
<p>JavaScript code can be compiled and run immediately or
compiled, saved, and run later.</p>
<p>A common use case is to run the code in a different V8 Context. This means
invoked code has a different global object than the invoking code.</p>
<p>One can provide the context by <a href="#what-does-it-mean-to-contextify-an-object"><em>contextifying</em></a> an
object. The invoked code treats any property in the context like a
global variable. Any changes to global variables caused by the invoked
code are reflected in the context object.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> x = <span class="hljs-number">1</span>;

<span class="hljs-keyword">const</span> context = { <span class="hljs-attr">x</span>: <span class="hljs-number">2</span> };
vm.<span class="hljs-title function_">createContext</span>(context); <span class="hljs-comment">// Contextify the object.</span>

<span class="hljs-keyword">const</span> code = <span class="hljs-string">'x += 40; var y = 17;'</span>;
<span class="hljs-comment">// `x` and `y` are global variables in the context.</span>
<span class="hljs-comment">// Initially, x has the value 2 because that is the value of context.x.</span>
vm.<span class="hljs-title function_">runInContext</span>(code, context);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">x</span>); <span class="hljs-comment">// 42</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">y</span>); <span class="hljs-comment">// 17</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(x); <span class="hljs-comment">// 1; y is not defined.</span></code> <button class="copy-button">copy</button></pre>
<section><h3>Class: <code>vm.Script</code><span><a class="mark" href="#class-vmscript" id="class-vmscript">#</a></span><a aria-hidden="true" class="legacy" id="vm_class_vm_script"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.1</span>
</div>
<p>Instances of the <code>vm.Script</code> class contain precompiled scripts that can be
executed in specific contexts.</p>
<h4><code>new vm.Script(code[, options])</code><span><a class="mark" href="#new-vmscriptcode-options" id="new-vmscriptcode-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_new_vm_script_code_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>v21.7.0, v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</p></td></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
<tr><td>v10.6.0</td>
<td><p>The <code>produceCachedData</code> is deprecated in favour of <code>script.createCachedData()</code>.</p></td></tr>
<tr><td>v5.7.0</td>
<td><p>The <code>cachedData</code> and <code>produceCachedData</code> options are supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The JavaScript code to compile.</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>
<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> Specifies the filename used in stack traces produced
by this script. <strong>Default:</strong> <code>'evalmachine.&#x3C;anonymous>'</code>.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the line number offset that is displayed
in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the first-line column number offset that
is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>cachedData</code> <a href="buffer.html#class-buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source. When supplied, the <code>cachedDataRejected</code> value will be set to
either <code>true</code> or <code>false</code> depending on acceptance of the data by V8.</li>
<li><code>produceCachedData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code> and no <code>cachedData</code> is present, V8
will attempt to produce code cache data for <code>code</code>. Upon success, a
<code>Buffer</code> with V8's code cache data will be produced and stored in the
<code>cachedData</code> property of the returned <code>vm.Script</code> instance.
The <code>cachedDataProduced</code> value will be set to either <code>true</code> or <code>false</code>
depending on whether code cache data is produced successfully.
This option is <strong>deprecated</strong> in favor of <code>script.createCachedData()</code>.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="vm.html#vmconstantsuse_main_context_default_loader" class="type">&#x3C;vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify how the modules should be loaded during the evaluation
of this script when <code>import()</code> is called. This option is part of the
experimental modules API. We do not recommend using it in a production
environment. For detailed information, see
<a href="#support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
</ul>
</li>
</ul>
<p>If <code>options</code> is a string, then it specifies the filename.</p>
<p>Creating a new <code>vm.Script</code> object compiles <code>code</code> but does not run it. The
compiled <code>vm.Script</code> can be run later multiple times. The <code>code</code> is not bound to
any global object; rather, it is bound before each run, just for that run.</p>
<h4><code>script.cachedDataRejected</code><span><a class="mark" href="#scriptcacheddatarejected" id="scriptcacheddatarejected">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_cacheddatarejected"></a></h4>
<div class="api_metadata">
<span>Added in: v5.7.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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></li>
</ul>
<p>When <code>cachedData</code> is supplied to create the <code>vm.Script</code>, this value will be set
to either <code>true</code> or <code>false</code> depending on acceptance of the data by V8.
Otherwise the value is <code>undefined</code>.</p>
<h4><code>script.createCachedData()</code><span><a class="mark" href="#scriptcreatecacheddata" id="scriptcreatecacheddata">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_createcacheddata"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li>Returns: <a href="buffer.html#class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Creates a code cache that can be used with the <code>Script</code> constructor's
<code>cachedData</code> option. Returns a <code>Buffer</code>. This method may be called at any
time and any number of times.</p>
<p>The code cache of the <code>Script</code> doesn't contain any JavaScript observable
states. The code cache is safe to be saved along side the script source and
used to construct new <code>Script</code> instances multiple times.</p>
<p>Functions in the <code>Script</code> source can be marked as lazily compiled and they are
not compiled at construction of the <code>Script</code>. These functions are going to be
compiled when they are invoked the first time. The code cache serializes the
metadata that V8 currently knows about the <code>Script</code> that it can use to speed up
future compilations.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">`
function add(a, b) {
  return a + b;
}

const x = add(1, 2);
`</span>);

<span class="hljs-keyword">const</span> cacheWithoutAdd = script.<span class="hljs-title function_">createCachedData</span>();
<span class="hljs-comment">// In `cacheWithoutAdd` the function `add()` is marked for full compilation</span>
<span class="hljs-comment">// upon invocation.</span>

script.<span class="hljs-title function_">runInThisContext</span>();

<span class="hljs-keyword">const</span> cacheWithAdd = script.<span class="hljs-title function_">createCachedData</span>();
<span class="hljs-comment">// `cacheWithAdd` contains fully compiled function `add()`.</span></code> <button class="copy-button">copy</button></pre>
<h4><code>script.runInContext(contextifiedObject[, options])</code><span><a class="mark" href="#scriptrunincontextcontextifiedobject-options" id="scriptrunincontextcontextifiedobject-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_runincontext_contextifiedobject_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>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>contextifiedObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> A <a href="#what-does-it-mean-to-contextify-an-object">contextified</a> object as returned by the
<code>vm.createContext()</code> method.</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>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code>, if an <a href="errors.html#class-error"><code>Error</code></a> occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="errors.html#class-error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</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>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> the result of the very last statement executed in the script.</li>
</ul>
<p>Runs the compiled code contained by the <code>vm.Script</code> object within the given
<code>contextifiedObject</code> and returns the result. Running code does not have access
to local scope.</p>
<p>The following example compiles code that increments a global variable, sets
the value of another global variable, then execute the code multiple times.
The globals are contained in the <code>context</code> object.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> context = {
  <span class="hljs-attr">animal</span>: <span class="hljs-string">'cat'</span>,
  <span class="hljs-attr">count</span>: <span class="hljs-number">2</span>,
};

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">'count += 1; name = "kitty";'</span>);

vm.<span class="hljs-title function_">createContext</span>(context);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">10</span>; ++i) {
  script.<span class="hljs-title function_">runInContext</span>(context);
}

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context);
<span class="hljs-comment">// Prints: { animal: 'cat', count: 12, name: 'kitty' }</span></code> <button class="copy-button">copy</button></pre>
<p>Using the <code>timeout</code> or <code>breakOnSigint</code> options will result in new event loops
and corresponding threads being started, which have a non-zero performance
overhead.</p>
<h4><code>script.runInNewContext([contextObject[, options]])</code><span><a class="mark" href="#scriptruninnewcontextcontextobject-options" id="scriptruninnewcontextcontextobject-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_runinnewcontext_contextobject_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>v22.8.0</td>
<td><p>The <code>contextObject</code> argument now accepts <code>vm.constants.DONT_CONTEXTIFY</code>.</p></td></tr>
<tr><td>v14.6.0</td>
<td><p>The <code>microtaskMode</code> option is supported now.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>contextCodeGeneration</code> option is supported now.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>contextObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="vm.html#vmconstantsdont_contextify" class="type">&#x3C;vm.constants.DONT_CONTEXTIFY></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a>
Either <a href="#vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a> or an object that will be <a href="#what-does-it-mean-to-contextify-an-object">contextified</a>.
If <code>undefined</code>, an empty contextified object will be created for backwards compatibility.</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>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code>, if an <a href="errors.html#class-error"><code>Error</code></a> occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="errors.html#class-error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</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>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <strong>Default:</strong> <code>false</code>.</li>
<li><code>contextName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Human-readable name of the newly created context.
<strong>Default:</strong> <code>'VM Context i'</code>, where <code>i</code> is an ascending numerical index of
the created context.</li>
<li><code>contextOrigin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <a href="https://developer.mozilla.org/en-US/docs/Glossary/Origin">Origin</a> corresponding to the newly
created context for display purposes. The origin should be formatted like a
URL, but with only the scheme, host, and port (if necessary), like the
value of the <a href="url.html#urlorigin"><code>url.origin</code></a> property of a <a href="url.html#class-url"><code>URL</code></a> object. Most notably,
this string should omit the trailing slash, as that denotes a path.
<strong>Default:</strong> <code>''</code>.</li>
<li><code>contextCodeGeneration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>strings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If set to false any calls to <code>eval</code> or function
constructors (<code>Function</code>, <code>GeneratorFunction</code>, etc) will throw an
<code>EvalError</code>. <strong>Default:</strong> <code>true</code>.</li>
<li><code>wasm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If set to false any attempt to compile a WebAssembly
module will throw a <code>WebAssembly.CompileError</code>. <strong>Default:</strong> <code>true</code>.</li>
</ul>
</li>
<li><code>microtaskMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> If set to <code>afterEvaluate</code>, microtasks (tasks
scheduled through <code>Promise</code>s and <code>async function</code>s) will be run immediately
after the script has run. They are included in the <code>timeout</code> and
<code>breakOnSigint</code> scopes in that case.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> the result of the very last statement executed in the script.</li>
</ul>
<p>This method is a shortcut to <code>script.runInContext(vm.createContext(options), options)</code>.
It does several things at once:</p>
<ol>
<li>Creates a new context.</li>
<li>If <code>contextObject</code> is an object, <a href="#what-does-it-mean-to-contextify-an-object">contextifies</a> it with the new context.
If  <code>contextObject</code> is undefined, creates a new object and <a href="#what-does-it-mean-to-contextify-an-object">contextifies</a> it.
If <code>contextObject</code> is <a href="#vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a>, don't <a href="#what-does-it-mean-to-contextify-an-object">contextify</a> anything.</li>
<li>Runs the compiled code contained by the <code>vm.Script</code> object within the created context. The code
does not have access to the scope in which this method is called.</li>
<li>Returns the result.</li>
</ol>
<p>The following example compiles code that sets a global variable, then executes
the code multiple times in different contexts. The globals are set on and
contained within each individual <code>context</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">'globalVar = "set"'</span>);

<span class="hljs-keyword">const</span> contexts = [{}, {}, {}];
contexts.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  script.<span class="hljs-title function_">runInNewContext</span>(context);
});

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contexts);
<span class="hljs-comment">// Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]</span>

<span class="hljs-comment">// This would throw if the context is created from a contextified object.</span>
<span class="hljs-comment">// vm.constants.DONT_CONTEXTIFY allows creating contexts with ordinary</span>
<span class="hljs-comment">// global objects that can be frozen.</span>
<span class="hljs-keyword">const</span> freezeScript = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">'Object.freeze(globalThis); globalThis;'</span>);
<span class="hljs-keyword">const</span> frozenContext = freezeScript.<span class="hljs-title function_">runInNewContext</span>(vm.<span class="hljs-property">constants</span>.<span class="hljs-property">DONT_CONTEXTIFY</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>script.runInThisContext([options])</code><span><a class="mark" href="#scriptruninthiscontextoptions" id="scriptruninthiscontextoptions">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_runinthiscontext_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>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</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>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code>, if an <a href="errors.html#class-error"><code>Error</code></a> occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="errors.html#class-error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</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>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> the result of the very last statement executed in the script.</li>
</ul>
<p>Runs the compiled code contained by the <code>vm.Script</code> within the context of the
current <code>global</code> object. Running code does not have access to local scope, but
<em>does</em> have access to the current <code>global</code> object.</p>
<p>The following example compiles code that increments a <code>global</code> variable then
executes that code multiple times:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-variable language_">global</span>.<span class="hljs-property">globalVar</span> = <span class="hljs-number">0</span>;

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">'globalVar += 1'</span>, { <span class="hljs-attr">filename</span>: <span class="hljs-string">'myfile.vm'</span> });

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">1000</span>; ++i) {
  script.<span class="hljs-title function_">runInThisContext</span>();
}

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(globalVar);

<span class="hljs-comment">// 1000</span></code> <button class="copy-button">copy</button></pre>
<h4><code>script.sourceMapURL</code><span><a class="mark" href="#scriptsourcemapurl" id="scriptsourcemapurl">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_sourcemapurl"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></li>
</ul>
<p>When the script is compiled from a source that contains a source map magic
comment, this property will be set to the URL of the source map.</p>

<pre class="with-30-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> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">`
function myFunc() {}
//# sourceMappingURL=sourcemap.json
`</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(script.<span class="hljs-property">sourceMapURL</span>);
<span class="hljs-comment">// Prints: sourcemap.json</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">`
function myFunc() {}
//# sourceMappingURL=sourcemap.json
`</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(script.<span class="hljs-property">sourceMapURL</span>);
<span class="hljs-comment">// Prints: sourcemap.json</span></code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>vm.Module</code><span><a class="mark" href="#class-vmmodule" id="class-vmmodule">#</a></span><a aria-hidden="true" class="legacy" id="vm_class_vm_module"></a></h3>
<div class="api_metadata">
<span>Added in: v13.0.0, v12.16.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>
<p>This feature is only available with the <code>--experimental-vm-modules</code> command
flag enabled.</p>
<p>The <code>vm.Module</code> class provides a low-level interface for using
ECMAScript modules in VM contexts. It is the counterpart of the <code>vm.Script</code>
class that closely mirrors <a href="https://262.ecma-international.org/14.0/#sec-abstract-module-records">Module Record</a>s as defined in the ECMAScript
specification.</p>
<p>Unlike <code>vm.Script</code> however, every <code>vm.Module</code> object is bound to a context from
its creation. Operations on <code>vm.Module</code> objects are intrinsically asynchronous,
in contrast with the synchronous nature of <code>vm.Script</code> objects. The use of
'async' functions can help with manipulating <code>vm.Module</code> objects.</p>
<p>Using a <code>vm.Module</code> object requires three distinct steps: creation/parsing,
linking, and evaluation. These three steps are illustrated in the following
example.</p>
<p>This implementation lies at a lower level than the <a href="esm.html#modules-ecmascript-modules">ECMAScript Module
loader</a>. There is also no way to interact with the Loader yet, though
support is planned.</p>

<pre class="with-30-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> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;

<span class="hljs-keyword">const</span> contextifiedObject = vm.<span class="hljs-title function_">createContext</span>({
  <span class="hljs-attr">secret</span>: <span class="hljs-number">42</span>,
  <span class="hljs-attr">print</span>: <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>,
});

<span class="hljs-comment">// Step 1</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Create a Module by constructing a new `vm.SourceTextModule` object. This</span>
<span class="hljs-comment">// parses the provided source text, throwing a `SyntaxError` if anything goes</span>
<span class="hljs-comment">// wrong. By default, a Module is created in the top context. But here, we</span>
<span class="hljs-comment">// specify `contextifiedObject` as the context this Module belongs to.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Here, we attempt to obtain the default export from the module "foo", and</span>
<span class="hljs-comment">// put it into local binding "secret".</span>

<span class="hljs-keyword">const</span> bar = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">`
  import s from 'foo';
  s;
  print(s);
`</span>, { <span class="hljs-attr">context</span>: contextifiedObject });

<span class="hljs-comment">// Step 2</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// "Link" the imported dependencies of this Module to it.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// The provided linking callback (the "linker") accepts two arguments: the</span>
<span class="hljs-comment">// parent module (`bar` in this case) and the string that is the specifier of</span>
<span class="hljs-comment">// the imported module. The callback is expected to return a Module that</span>
<span class="hljs-comment">// corresponds to the provided specifier, with certain requirements documented</span>
<span class="hljs-comment">// in `module.link()`.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// If linking has not started for the returned Module, the same linker</span>
<span class="hljs-comment">// callback will be called on the returned Module.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Even top-level Modules without dependencies must be explicitly linked. The</span>
<span class="hljs-comment">// callback provided would never be called, however.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// The link() method returns a Promise that will be resolved when all the</span>
<span class="hljs-comment">// Promises returned by the linker resolve.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Note: This is a contrived example in that the linker function creates a new</span>
<span class="hljs-comment">// "foo" module every time it is called. In a full-fledged module system, a</span>
<span class="hljs-comment">// cache would probably be used to avoid duplicated modules.</span>

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">linker</span>(<span class="hljs-params">specifier, referencingModule</span>) {
  <span class="hljs-keyword">if</span> (specifier === <span class="hljs-string">'foo'</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">`
      // The "secret" variable refers to the global variable we added to
      // "contextifiedObject" when creating the context.
      export default secret;
    `</span>, { <span class="hljs-attr">context</span>: referencingModule.<span class="hljs-property">context</span> });

    <span class="hljs-comment">// Using `contextifiedObject` instead of `referencingModule.context`</span>
    <span class="hljs-comment">// here would work as well.</span>
  }
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">`Unable to resolve dependency: <span class="hljs-subst">${specifier}</span>`</span>);
}
<span class="hljs-keyword">await</span> bar.<span class="hljs-title function_">link</span>(linker);

<span class="hljs-comment">// Step 3</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Evaluate the Module. The evaluate() method returns a promise which will</span>
<span class="hljs-comment">// resolve after the module has finished evaluating.</span>

<span class="hljs-comment">// Prints 42.</span>
<span class="hljs-keyword">await</span> bar.<span class="hljs-title function_">evaluate</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> contextifiedObject = vm.<span class="hljs-title function_">createContext</span>({
  <span class="hljs-attr">secret</span>: <span class="hljs-number">42</span>,
  <span class="hljs-attr">print</span>: <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>,
});

(<span class="hljs-title function_">async</span> () => {
  <span class="hljs-comment">// Step 1</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// Create a Module by constructing a new `vm.SourceTextModule` object. This</span>
  <span class="hljs-comment">// parses the provided source text, throwing a `SyntaxError` if anything goes</span>
  <span class="hljs-comment">// wrong. By default, a Module is created in the top context. But here, we</span>
  <span class="hljs-comment">// specify `contextifiedObject` as the context this Module belongs to.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// Here, we attempt to obtain the default export from the module "foo", and</span>
  <span class="hljs-comment">// put it into local binding "secret".</span>

  <span class="hljs-keyword">const</span> bar = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">`
    import s from 'foo';
    s;
    print(s);
  `</span>, { <span class="hljs-attr">context</span>: contextifiedObject });

  <span class="hljs-comment">// Step 2</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// "Link" the imported dependencies of this Module to it.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// The provided linking callback (the "linker") accepts two arguments: the</span>
  <span class="hljs-comment">// parent module (`bar` in this case) and the string that is the specifier of</span>
  <span class="hljs-comment">// the imported module. The callback is expected to return a Module that</span>
  <span class="hljs-comment">// corresponds to the provided specifier, with certain requirements documented</span>
  <span class="hljs-comment">// in `module.link()`.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// If linking has not started for the returned Module, the same linker</span>
  <span class="hljs-comment">// callback will be called on the returned Module.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// Even top-level Modules without dependencies must be explicitly linked. The</span>
  <span class="hljs-comment">// callback provided would never be called, however.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// The link() method returns a Promise that will be resolved when all the</span>
  <span class="hljs-comment">// Promises returned by the linker resolve.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// Note: This is a contrived example in that the linker function creates a new</span>
  <span class="hljs-comment">// "foo" module every time it is called. In a full-fledged module system, a</span>
  <span class="hljs-comment">// cache would probably be used to avoid duplicated modules.</span>

  <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">linker</span>(<span class="hljs-params">specifier, referencingModule</span>) {
    <span class="hljs-keyword">if</span> (specifier === <span class="hljs-string">'foo'</span>) {
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">`
        // The "secret" variable refers to the global variable we added to
        // "contextifiedObject" when creating the context.
        export default secret;
      `</span>, { <span class="hljs-attr">context</span>: referencingModule.<span class="hljs-property">context</span> });

      <span class="hljs-comment">// Using `contextifiedObject` instead of `referencingModule.context`</span>
      <span class="hljs-comment">// here would work as well.</span>
    }
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">`Unable to resolve dependency: <span class="hljs-subst">${specifier}</span>`</span>);
  }
  <span class="hljs-keyword">await</span> bar.<span class="hljs-title function_">link</span>(linker);

  <span class="hljs-comment">// Step 3</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// Evaluate the Module. The evaluate() method returns a promise which will</span>
  <span class="hljs-comment">// resolve after the module has finished evaluating.</span>

  <span class="hljs-comment">// Prints 42.</span>
  <span class="hljs-keyword">await</span> bar.<span class="hljs-title function_">evaluate</span>();
})();</code><button class="copy-button">copy</button></pre>
<h4><code>module.dependencySpecifiers</code><span><a class="mark" href="#moduledependencyspecifiers" id="moduledependencyspecifiers">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_dependencyspecifiers"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>The specifiers of all dependencies of this module. The returned array is frozen
to disallow any changes to it.</p>
<p>Corresponds to the <code>[[RequestedModules]]</code> field of <a href="https://tc39.es/ecma262/#sec-cyclic-module-records">Cyclic Module Record</a>s in
the ECMAScript specification.</p>
<h4><code>module.error</code><span><a class="mark" href="#moduleerror" id="moduleerror">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_error"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>If the <code>module.status</code> is <code>'errored'</code>, this property contains the exception
thrown by the module during evaluation. If the status is anything else,
accessing this property will result in a thrown exception.</p>
<p>The value <code>undefined</code> cannot be used for cases where there is not a thrown
exception due to possible ambiguity with <code>throw undefined;</code>.</p>
<p>Corresponds to the <code>[[EvaluationError]]</code> field of <a href="https://tc39.es/ecma262/#sec-cyclic-module-records">Cyclic Module Record</a>s
in the ECMAScript specification.</p>
<h4><code>module.evaluate([options])</code><span><a class="mark" href="#moduleevaluateoptions" id="moduleevaluateoptions">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_evaluate_options"></a></h4>
<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>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Specifies the number of milliseconds to evaluate
before terminating execution. If execution is interrupted, an <a href="errors.html#class-error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</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>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <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> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Evaluate the module.</p>
<p>This must be called after the module has been linked; otherwise it will reject.
It could be called also when the module has already been evaluated, in which
case it will either do nothing if the initial evaluation ended in success
(<code>module.status</code> is <code>'evaluated'</code>) or it will re-throw the exception that the
initial evaluation resulted in (<code>module.status</code> is <code>'errored'</code>).</p>
<p>This method cannot be called while the module is being evaluated
(<code>module.status</code> is <code>'evaluating'</code>).</p>
<p>Corresponds to the <a href="https://tc39.es/ecma262/#sec-moduleevaluation">Evaluate() concrete method</a> field of <a href="https://tc39.es/ecma262/#sec-cyclic-module-records">Cyclic Module
Record</a>s in the ECMAScript specification.</p>
<h4><code>module.identifier</code><span><a class="mark" href="#moduleidentifier" id="moduleidentifier">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_identifier"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The identifier of the current module, as set in the constructor.</p>
<h4><code>module.link(linker)</code><span><a class="mark" href="#modulelinklinker" id="modulelinklinker">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_link_linker"></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.1.0, v20.10.0, v18.19.0</td>
<td><p>The option <code>extra.assert</code> is renamed to <code>extra.attributes</code>. The former name is still provided for backward compatibility.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>linker</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<ul>
<li>
<p><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The specifier of the requested module:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> foo <span class="hljs-keyword">from</span> <span class="hljs-string">'foo'</span>;
<span class="hljs-comment">//              ^^^^^ the module specifier</span></code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p><code>referencingModule</code> <a href="vm.html#class-vmmodule" class="type">&#x3C;vm.Module></a> The <code>Module</code> object <code>link()</code> is called on.</p>
</li>
<li>
<p><code>extra</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>attributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The data from the attribute:
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> foo <span class="hljs-keyword">from</span> <span class="hljs-string">'foo'</span> <span class="hljs-keyword">with</span> { <span class="hljs-attr">name</span>: <span class="hljs-string">'value'</span> };
<span class="hljs-comment">//                         ^^^^^^^^^^^^^^^^^ the attribute</span></code> <button class="copy-button">copy</button></pre>
Per ECMA-262, hosts are expected to trigger an error if an
unsupported attribute is present.</li>
<li><code>assert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Alias for <code>extra.attributes</code>.</li>
</ul>
</li>
<li>
<p>Returns: <a href="vm.html#class-vmmodule" class="type">&#x3C;vm.Module></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></p>
</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></li>
</ul>
<p>Link module dependencies. This method must be called before evaluation, and
can only be called once per module.</p>
<p>The function is expected to return a <code>Module</code> object or a <code>Promise</code> that
eventually resolves to a <code>Module</code> object. The returned <code>Module</code> must satisfy the
following two invariants:</p>
<ul>
<li>It must belong to the same context as the parent <code>Module</code>.</li>
<li>Its <code>status</code> must not be <code>'errored'</code>.</li>
</ul>
<p>If the returned <code>Module</code>'s <code>status</code> is <code>'unlinked'</code>, this method will be
recursively called on the returned <code>Module</code> with the same provided <code>linker</code>
function.</p>
<p><code>link()</code> returns a <code>Promise</code> that will either get resolved when all linking
instances resolve to a valid <code>Module</code>, or rejected if the linker function either
throws an exception or returns an invalid <code>Module</code>.</p>
<p>The linker function roughly corresponds to the implementation-defined
<a href="https://tc39.es/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> abstract operation in the ECMAScript
specification, with a few key differences:</p>
<ul>
<li>The linker function is allowed to be asynchronous while
<a href="https://tc39.es/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> is synchronous.</li>
</ul>
<p>The actual <a href="https://tc39.es/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> implementation used during module
linking is one that returns the modules linked during linking. Since at
that point all modules would have been fully linked already, the
<a href="https://tc39.es/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> implementation is fully synchronous per
specification.</p>
<p>Corresponds to the <a href="https://tc39.es/ecma262/#sec-moduledeclarationlinking">Link() concrete method</a> field of <a href="https://tc39.es/ecma262/#sec-cyclic-module-records">Cyclic Module
Record</a>s in the ECMAScript specification.</p>
<h4><code>module.namespace</code><span><a class="mark" href="#modulenamespace" id="modulenamespace">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_namespace"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>The namespace object of the module. This is only available after linking
(<code>module.link()</code>) has completed.</p>
<p>Corresponds to the <a href="https://tc39.es/ecma262/#sec-getmodulenamespace">GetModuleNamespace</a> abstract operation in the ECMAScript
specification.</p>
<h4><code>module.status</code><span><a class="mark" href="#modulestatus" id="modulestatus">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_status"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The current status of the module. Will be one of:</p>
<ul>
<li>
<p><code>'unlinked'</code>: <code>module.link()</code> has not yet been called.</p>
</li>
<li>
<p><code>'linking'</code>: <code>module.link()</code> has been called, but not all Promises returned
by the linker function have been resolved yet.</p>
</li>
<li>
<p><code>'linked'</code>: The module has been linked successfully, and all of its
dependencies are linked, but <code>module.evaluate()</code> has not yet been called.</p>
</li>
<li>
<p><code>'evaluating'</code>: The module is being evaluated through a <code>module.evaluate()</code> on
itself or a parent module.</p>
</li>
<li>
<p><code>'evaluated'</code>: The module has been successfully evaluated.</p>
</li>
<li>
<p><code>'errored'</code>: The module has been evaluated, but an exception was thrown.</p>
</li>
</ul>
<p>Other than <code>'errored'</code>, this status string corresponds to the specification's
<a href="https://tc39.es/ecma262/#sec-cyclic-module-records">Cyclic Module Record</a>'s <code>[[Status]]</code> field. <code>'errored'</code> corresponds to
<code>'evaluated'</code> in the specification, but with <code>[[EvaluationError]]</code> set to a
value that is not <code>undefined</code>.</p>
</section><section><h3>Class: <code>vm.SourceTextModule</code><span><a class="mark" href="#class-vmsourcetextmodule" id="class-vmsourcetextmodule">#</a></span><a aria-hidden="true" class="legacy" id="vm_class_vm_sourcetextmodule"></a></h3>
<div class="api_metadata">
<span>Added in: v9.6.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>
<p>This feature is only available with the <code>--experimental-vm-modules</code> command
flag enabled.</p>
<ul>
<li>Extends: <a href="vm.html#class-vmmodule" class="type">&#x3C;vm.Module></a></li>
</ul>
<p>The <code>vm.SourceTextModule</code> class provides the <a href="https://tc39.es/ecma262/#sec-source-text-module-records">Source Text Module Record</a> as
defined in the ECMAScript specification.</p>
<h4><code>new vm.SourceTextModule(code[, options])</code><span><a class="mark" href="#new-vmsourcetextmodulecode-options" id="new-vmsourcetextmodulecode-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_new_vm_sourcetextmodule_code_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>v17.0.0, v16.12.0</td>
<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> JavaScript Module code to parse</li>
<li><code>options</code>
<ul>
<li><code>identifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> String used in stack traces.
<strong>Default:</strong> <code>'vm:module(i)'</code> where <code>i</code> is a context-specific ascending
index.</li>
<li><code>cachedData</code> <a href="buffer.html#class-buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source. The <code>code</code> must be the same as the module from which this
<code>cachedData</code> was created.</li>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The <a href="#what-does-it-mean-to-contextify-an-object">contextified</a> object as returned by the
<code>vm.createContext()</code> method, to compile and evaluate this <code>Module</code> in.
If no context is specified, the module is evaluated in the current
execution context.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Specifies the line number offset that is displayed
in stack traces produced by this <code>Module</code>. <strong>Default:</strong> <code>0</code>.</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Specifies the first-line column number offset that
is displayed in stack traces produced by this <code>Module</code>. <strong>Default:</strong> <code>0</code>.</li>
<li><code>initializeImportMeta</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Called during evaluation of this <code>Module</code>
to initialize the <code>import.meta</code>.
<ul>
<li><code>meta</code> <a href="esm.html#importmeta" class="type">&#x3C;import.meta></a></li>
<li><code>module</code> <a href="vm.html#class-vmsourcetextmodule" class="type">&#x3C;vm.SourceTextModule></a></li>
</ul>
</li>
<li><code>importModuleDynamically</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Used to specify the
how the modules should be loaded during the evaluation of this module
when <code>import()</code> is called. This option is part of the experimental
modules API. We do not recommend using it in a production environment.
For detailed information, see
<a href="#support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
</ul>
</li>
</ul>
<p>Creates a new <code>SourceTextModule</code> instance.</p>
<p>Properties assigned to the <code>import.meta</code> object that are objects may
allow the module to access information outside the specified <code>context</code>. Use
<code>vm.runInContext()</code> to create objects in a specific context.</p>

<pre class="with-60-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> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;

<span class="hljs-keyword">const</span> contextifiedObject = vm.<span class="hljs-title function_">createContext</span>({ <span class="hljs-attr">secret</span>: <span class="hljs-number">42</span> });

<span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(
  <span class="hljs-string">'Object.getPrototypeOf(import.meta.prop).secret = secret;'</span>,
  {
    <span class="hljs-title function_">initializeImportMeta</span>(<span class="hljs-params">meta</span>) {
      <span class="hljs-comment">// Note: this object is created in the top context. As such,</span>
      <span class="hljs-comment">// Object.getPrototypeOf(import.meta.prop) points to the</span>
      <span class="hljs-comment">// Object.prototype in the top context rather than that in</span>
      <span class="hljs-comment">// the contextified object.</span>
      meta.<span class="hljs-property">prop</span> = {};
    },
  });
<span class="hljs-comment">// Since module has no dependencies, the linker function will never be called.</span>
<span class="hljs-keyword">await</span> <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> {});
<span class="hljs-keyword">await</span> <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">evaluate</span>();

<span class="hljs-comment">// Now, Object.prototype.secret will be equal to 42.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// To fix this problem, replace</span>
<span class="hljs-comment">//     meta.prop = {};</span>
<span class="hljs-comment">// above with</span>
<span class="hljs-comment">//     meta.prop = vm.runInContext('{}', contextifiedObject);</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> contextifiedObject = vm.<span class="hljs-title function_">createContext</span>({ <span class="hljs-attr">secret</span>: <span class="hljs-number">42</span> });
(<span class="hljs-title function_">async</span> () => {
  <span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(
    <span class="hljs-string">'Object.getPrototypeOf(import.meta.prop).secret = secret;'</span>,
    {
      <span class="hljs-title function_">initializeImportMeta</span>(<span class="hljs-params">meta</span>) {
        <span class="hljs-comment">// Note: this object is created in the top context. As such,</span>
        <span class="hljs-comment">// Object.getPrototypeOf(import.meta.prop) points to the</span>
        <span class="hljs-comment">// Object.prototype in the top context rather than that in</span>
        <span class="hljs-comment">// the contextified object.</span>
        meta.<span class="hljs-property">prop</span> = {};
      },
    });
  <span class="hljs-comment">// Since module has no dependencies, the linker function will never be called.</span>
  <span class="hljs-keyword">await</span> <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> {});
  <span class="hljs-keyword">await</span> <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">evaluate</span>();
  <span class="hljs-comment">// Now, Object.prototype.secret will be equal to 42.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// To fix this problem, replace</span>
  <span class="hljs-comment">//     meta.prop = {};</span>
  <span class="hljs-comment">// above with</span>
  <span class="hljs-comment">//     meta.prop = vm.runInContext('{}', contextifiedObject);</span>
})();</code><button class="copy-button">copy</button></pre>
<h4><code>sourceTextModule.createCachedData()</code><span><a class="mark" href="#sourcetextmodulecreatecacheddata" id="sourcetextmodulecreatecacheddata">#</a></span><a aria-hidden="true" class="legacy" id="vm_sourcetextmodule_createcacheddata"></a></h4>
<div class="api_metadata">
<span>Added in: v13.7.0, v12.17.0</span>
</div>
<ul>
<li>Returns: <a href="buffer.html#class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Creates a code cache that can be used with the <code>SourceTextModule</code> constructor's
<code>cachedData</code> option. Returns a <code>Buffer</code>. This method may be called any number
of times before the module has been evaluated.</p>
<p>The code cache of the <code>SourceTextModule</code> doesn't contain any JavaScript
observable states. The code cache is safe to be saved along side the script
source and used to construct new <code>SourceTextModule</code> instances multiple times.</p>
<p>Functions in the <code>SourceTextModule</code> source can be marked as lazily compiled
and they are not compiled at construction of the <code>SourceTextModule</code>. These
functions are going to be compiled when they are invoked the first time. The
code cache serializes the metadata that V8 currently knows about the
<code>SourceTextModule</code> that it can use to speed up future compilations.</p>
<pre><code class="language-js"><span class="hljs-comment">// Create an initial module</span>
<span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">'const a = 1;'</span>);

<span class="hljs-comment">// Create cached data from this module</span>
<span class="hljs-keyword">const</span> cachedData = <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">createCachedData</span>();

<span class="hljs-comment">// Create a new module using the cached data. The code must be the same.</span>
<span class="hljs-keyword">const</span> module2 = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">'const a = 1;'</span>, { cachedData });</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>vm.SyntheticModule</code><span><a class="mark" href="#class-vmsyntheticmodule" id="class-vmsyntheticmodule">#</a></span><a aria-hidden="true" class="legacy" id="vm_class_vm_syntheticmodule"></a></h3>
<div class="api_metadata">
<span>Added in: v13.0.0, v12.16.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>
<p>This feature is only available with the <code>--experimental-vm-modules</code> command
flag enabled.</p>
<ul>
<li>Extends: <a href="vm.html#class-vmmodule" class="type">&#x3C;vm.Module></a></li>
</ul>
<p>The <code>vm.SyntheticModule</code> class provides the <a href="https://heycam.github.io/webidl/#synthetic-module-records">Synthetic Module Record</a> as
defined in the WebIDL specification. The purpose of synthetic modules is to
provide a generic interface for exposing non-JavaScript sources to ECMAScript
module graphs.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> source = <span class="hljs-string">'{ "a": 1 }'</span>;
<span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SyntheticModule</span>([<span class="hljs-string">'default'</span>], <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> obj = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(source);
  <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'default'</span>, obj);
});

<span class="hljs-comment">// Use `module` in linking...</span></code> <button class="copy-button">copy</button></pre>
<h4><code>new vm.SyntheticModule(exportNames, evaluateCallback[, options])</code><span><a class="mark" href="#new-vmsyntheticmoduleexportnames-evaluatecallback-options" id="new-vmsyntheticmoduleexportnames-evaluatecallback-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_new_vm_syntheticmodule_exportnames_evaluatecallback_options"></a></h4>
<div class="api_metadata">
<span>Added in: v13.0.0, v12.16.0</span>
</div>
<ul>
<li><code>exportNames</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> Array of names that will be exported from the
module.</li>
<li><code>evaluateCallback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Called when the module is evaluated.</li>
<li><code>options</code>
<ul>
<li><code>identifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> String used in stack traces.
<strong>Default:</strong> <code>'vm:module(i)'</code> where <code>i</code> is a context-specific ascending
index.</li>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The <a href="#what-does-it-mean-to-contextify-an-object">contextified</a> object as returned by the
<code>vm.createContext()</code> method, to compile and evaluate this <code>Module</code> in.</li>
</ul>
</li>
</ul>
<p>Creates a new <code>SyntheticModule</code> instance.</p>
<p>Objects assigned to the exports of this instance may allow importers of
the module to access information outside the specified <code>context</code>. Use
<code>vm.runInContext()</code> to create objects in a specific context.</p>
<h4><code>syntheticModule.setExport(name, value)</code><span><a class="mark" href="#syntheticmodulesetexportname-value" id="syntheticmodulesetexportname-value">#</a></span><a aria-hidden="true" class="legacy" id="vm_syntheticmodule_setexport_name_value"></a></h4>
<div class="api_metadata">
<span>Added in: v13.0.0, v12.16.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Name of the export to set.</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 set the export to.</li>
</ul>
<p>This method is used after the module is linked to set the values of exports. If
it is called before the module is linked, an <a href="errors.html#err_vm_module_status"><code>ERR_VM_MODULE_STATUS</code></a> error
will be thrown.</p>

<pre class="with-30-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> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;

<span class="hljs-keyword">const</span> m = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SyntheticModule</span>([<span class="hljs-string">'x'</span>], <span class="hljs-function">() =></span> {
  m.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'x'</span>, <span class="hljs-number">1</span>);
});

<span class="hljs-keyword">await</span> m.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> {});
<span class="hljs-keyword">await</span> m.<span class="hljs-title function_">evaluate</span>();

assert.<span class="hljs-title function_">strictEqual</span>(m.<span class="hljs-property">namespace</span>.<span class="hljs-property">x</span>, <span class="hljs-number">1</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
(<span class="hljs-title function_">async</span> () => {
  <span class="hljs-keyword">const</span> m = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SyntheticModule</span>([<span class="hljs-string">'x'</span>], <span class="hljs-function">() =></span> {
    m.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'x'</span>, <span class="hljs-number">1</span>);
  });
  <span class="hljs-keyword">await</span> m.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> {});
  <span class="hljs-keyword">await</span> m.<span class="hljs-title function_">evaluate</span>();
  assert.<span class="hljs-title function_">strictEqual</span>(m.<span class="hljs-property">namespace</span>.<span class="hljs-property">x</span>, <span class="hljs-number">1</span>);
})();</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>vm.compileFunction(code[, params[, options]])</code><span><a class="mark" href="#vmcompilefunctioncode-params-options" id="vmcompilefunctioncode-params-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_compilefunction_code_params_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v21.7.0, v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</p></td></tr>
<tr><td>v19.6.0, v18.15.0</td>
<td><p>The return value now includes <code>cachedDataRejected</code> with the same semantics as the <code>vm.Script</code> version if the <code>cachedData</code> option was passed.</p></td></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
<tr><td>v15.9.0</td>
<td><p>Added <code>importModuleDynamically</code> option again.</p></td></tr>
<tr><td>v14.3.0</td>
<td><p>Removal of <code>importModuleDynamically</code> due to compatibility issues.</p></td></tr>
<tr><td>v14.1.0, v13.14.0</td>
<td><p>The <code>importModuleDynamically</code> option is now supported.</p></td></tr>
<tr><td>v10.10.0</td>
<td><p><span>Added in: v10.10.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The body of the function to compile.</li>
<li><code>params</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> An array of strings containing all parameters for the
function.</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>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Specifies the filename used in stack traces produced
by this script. <strong>Default:</strong> <code>''</code>.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the line number offset that is displayed
in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the first-line column number offset that
is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>cachedData</code> <a href="buffer.html#class-buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source. This must be produced by a prior call to <a href="#vmcompilefunctioncode-params-options"><code>vm.compileFunction()</code></a>
with the same <code>code</code> and <code>params</code>.</li>
<li><code>produceCachedData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Specifies whether to produce new cache data.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>parsingContext</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The <a href="#what-does-it-mean-to-contextify-an-object">contextified</a> object in which the said
function should be compiled in.</li>
<li><code>contextExtensions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a> An array containing a collection of context
extensions (objects wrapping the current scope) to be applied while
compiling. <strong>Default:</strong> <code>[]</code>.</li>
</ul>
</li>
<li><code>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="vm.html#vmconstantsuse_main_context_default_loader" class="type">&#x3C;vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify the how the modules should be loaded during the evaluation of
this function when <code>import()</code> is called. This option is part of the
experimental modules API. We do not recommend using it in a production
environment. For detailed information, see
<a href="#support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<p>Compiles the given code into the provided context (if no context is
supplied, the current context is used), and returns it wrapped inside a
function with the given <code>params</code>.</p>
</section><section><h3><code>vm.constants</code><span><a class="mark" href="#vmconstants" id="vmconstants">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_constants"></a></h3>
<div class="api_metadata">
<span>Added in: v21.7.0, v20.12.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></li>
</ul>
<p>Returns an object containing commonly used constants for VM operations.</p>
<h4><code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code><span><a class="mark" href="#vmconstantsuse_main_context_default_loader" id="vmconstantsuse_main_context_default_loader">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_constants_use_main_context_default_loader"></a></h4>
<div class="api_metadata">
<span>Added in: v21.7.0, v20.12.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>
<p>A constant that can be used as the <code>importModuleDynamically</code> option to
<code>vm.Script</code> and <code>vm.compileFunction()</code> so that Node.js uses the default
ESM loader from the main context to load the requested module.</p>
<p>For detailed information, see
<a href="#support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</p>
</section><section><h3><code>vm.createContext([contextObject[, options]])</code><span><a class="mark" href="#vmcreatecontextcontextobject-options" id="vmcreatecontextcontextobject-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_createcontext_contextobject_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v22.8.0</td>
<td><p>The <code>contextObject</code> argument now accepts <code>vm.constants.DONT_CONTEXTIFY</code>.</p></td></tr>
<tr><td>v21.7.0, v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</p></td></tr>
<tr><td>v21.2.0, v20.11.0</td>
<td><p>The <code>importModuleDynamically</code> option is supported now.</p></td></tr>
<tr><td>v14.6.0</td>
<td><p>The <code>microtaskMode</code> option is supported now.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The first argument can no longer be a function.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>codeGeneration</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>contextObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="vm.html#vmconstantsdont_contextify" class="type">&#x3C;vm.constants.DONT_CONTEXTIFY></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a>
Either <a href="#vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a> or an object that will be <a href="#what-does-it-mean-to-contextify-an-object">contextified</a>.
If <code>undefined</code>, an empty contextified object will be created for backwards compatibility.</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>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Human-readable name of the newly created context.
<strong>Default:</strong> <code>'VM Context i'</code>, where <code>i</code> is an ascending numerical index of
the created context.</li>
<li><code>origin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <a href="https://developer.mozilla.org/en-US/docs/Glossary/Origin">Origin</a> corresponding to the newly created
context for display purposes. The origin should be formatted like a URL,
but with only the scheme, host, and port (if necessary), like the value of
the <a href="url.html#urlorigin"><code>url.origin</code></a> property of a <a href="url.html#class-url"><code>URL</code></a> object. Most notably, this
string should omit the trailing slash, as that denotes a path.
<strong>Default:</strong> <code>''</code>.</li>
<li><code>codeGeneration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>strings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If set to false any calls to <code>eval</code> or function
constructors (<code>Function</code>, <code>GeneratorFunction</code>, etc) will throw an
<code>EvalError</code>. <strong>Default:</strong> <code>true</code>.</li>
<li><code>wasm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If set to false any attempt to compile a WebAssembly
module will throw a <code>WebAssembly.CompileError</code>. <strong>Default:</strong> <code>true</code>.</li>
</ul>
</li>
<li><code>microtaskMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> If set to <code>afterEvaluate</code>, microtasks (tasks
scheduled through <code>Promise</code>s and <code>async function</code>s) will be run immediately
after a script has run through <a href="#scriptrunincontextcontextifiedobject-options"><code>script.runInContext()</code></a>.
They are included in the <code>timeout</code> and <code>breakOnSigint</code> scopes in that case.</li>
<li><code>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="vm.html#vmconstantsuse_main_context_default_loader" class="type">&#x3C;vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify the how the modules should be loaded when <code>import()</code> is
called in this context without a referrer script or module. This option is
part of the experimental modules API. We do not recommend using it in a
production environment. For detailed information, see
<a href="#support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> contextified object.</li>
</ul>
<p>If the given <code>contextObject</code> is an object, the <code>vm.createContext()</code> method will <a href="#what-does-it-mean-to-contextify-an-object">prepare that
object</a> and return a reference to it so that it can be used in
calls to <a href="#vmrunincontextcode-contextifiedobject-options"><code>vm.runInContext()</code></a> or <a href="#scriptrunincontextcontextifiedobject-options"><code>script.runInContext()</code></a>. Inside such
scripts, the global object will be wrapped by the <code>contextObject</code>, retaining all of its
existing properties but also having the built-in objects and functions any
standard <a href="https://es5.github.io/#x15.1">global object</a> has. Outside of scripts run by the vm module, global
variables will remain unchanged.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-variable language_">global</span>.<span class="hljs-property">globalVar</span> = <span class="hljs-number">3</span>;

<span class="hljs-keyword">const</span> context = { <span class="hljs-attr">globalVar</span>: <span class="hljs-number">1</span> };
vm.<span class="hljs-title function_">createContext</span>(context);

vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalVar *= 2;'</span>, context);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context);
<span class="hljs-comment">// Prints: { globalVar: 2 }</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-variable language_">global</span>.<span class="hljs-property">globalVar</span>);
<span class="hljs-comment">// Prints: 3</span></code> <button class="copy-button">copy</button></pre>
<p>If <code>contextObject</code> is omitted (or passed explicitly as <code>undefined</code>), a new,
empty <a href="#what-does-it-mean-to-contextify-an-object">contextified</a> object will be returned.</p>
<p>When the global object in the newly created context is <a href="#what-does-it-mean-to-contextify-an-object">contextified</a>, it has some quirks
compared to ordinary global objects. For example, it cannot be frozen. To create a context
without the contextifying quirks, pass <a href="#vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a> as the <code>contextObject</code>
argument. See the documentation of <a href="#vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a> for details.</p>
<p>The <code>vm.createContext()</code> method is primarily useful for creating a single
context that can be used to run multiple scripts. For instance, if emulating a
web browser, the method can be used to create a single context representing a
window's global object, then run all <code>&#x3C;script></code> tags together within that
context.</p>
<p>The provided <code>name</code> and <code>origin</code> of the context are made visible through the
Inspector API.</p>
</section><section><h3><code>vm.isContext(object)</code><span><a class="mark" href="#vmiscontextobject" id="vmiscontextobject">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_iscontext_object"></a></h3>
<div class="api_metadata">
<span>Added in: v0.11.7</span>
</div>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></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>Returns <code>true</code> if the given <code>object</code> object has been <a href="#what-does-it-mean-to-contextify-an-object">contextified</a> using
<a href="#vmcreatecontextcontextobject-options"><code>vm.createContext()</code></a>, or if it's the global object of a context created
using <a href="#vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a>.</p>
</section><section><h3><code>vm.measureMemory([options])</code><span><a class="mark" href="#vmmeasurememoryoptions" id="vmmeasurememoryoptions">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_measurememory_options"></a></h3>
<div class="api_metadata">
<span>Added in: v13.10.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>
<p>Measure the memory known to V8 and used by all contexts known to the
current V8 isolate, or the main context.</p>
<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> Optional.
<ul>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Either <code>'summary'</code> or <code>'detailed'</code>. In summary mode,
only the memory measured for the main context will be returned. In
detailed mode, the memory measured for all contexts known to the
current V8 isolate will be returned.
<strong>Default:</strong> <code>'summary'</code></li>
<li><code>execution</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Either <code>'default'</code> or <code>'eager'</code>. With default
execution, the promise will not resolve until after the next scheduled
garbage collection starts, which may take a while (or never if the program
exits before the next GC). With eager execution, the GC will be started
right away to measure the memory.
<strong>Default:</strong> <code>'default'</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> If the memory is successfully measured, the promise will
resolve with an object containing information about the memory usage.
Otherwise it will be rejected with an <code>ERR_CONTEXT_NOT_INITIALIZED</code> error.</li>
</ul>
<p>The format of the object that the returned Promise may resolve with is
specific to the V8 engine and may change from one version of V8 to the next.</p>
<p>The returned result is different from the statistics returned by
<code>v8.getHeapSpaceStatistics()</code> in that <code>vm.measureMemory()</code> measure the
memory reachable by each V8 specific contexts in the current instance of
the V8 engine, while the result of <code>v8.getHeapSpaceStatistics()</code> measure
the memory occupied by each heap space in the current V8 instance.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-comment">// Measure the memory used by the main context.</span>
vm.<span class="hljs-title function_">measureMemory</span>({ <span class="hljs-attr">mode</span>: <span class="hljs-string">'summary'</span> })
  <span class="hljs-comment">// This is the same as vm.measureMemory()</span>
  .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
    <span class="hljs-comment">// The current format is:</span>
    <span class="hljs-comment">// {</span>
    <span class="hljs-comment">//   total: {</span>
    <span class="hljs-comment">//      jsMemoryEstimate: 2418479, jsMemoryRange: [ 2418479, 2745799 ]</span>
    <span class="hljs-comment">//    }</span>
    <span class="hljs-comment">// }</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);
  });

<span class="hljs-keyword">const</span> context = vm.<span class="hljs-title function_">createContext</span>({ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> });
vm.<span class="hljs-title function_">measureMemory</span>({ <span class="hljs-attr">mode</span>: <span class="hljs-string">'detailed'</span>, <span class="hljs-attr">execution</span>: <span class="hljs-string">'eager'</span> })
  .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
    <span class="hljs-comment">// Reference the context here so that it won't be GC'ed</span>
    <span class="hljs-comment">// until the measurement is complete.</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">a</span>);
    <span class="hljs-comment">// {</span>
    <span class="hljs-comment">//   total: {</span>
    <span class="hljs-comment">//     jsMemoryEstimate: 2574732,</span>
    <span class="hljs-comment">//     jsMemoryRange: [ 2574732, 2904372 ]</span>
    <span class="hljs-comment">//   },</span>
    <span class="hljs-comment">//   current: {</span>
    <span class="hljs-comment">//     jsMemoryEstimate: 2438996,</span>
    <span class="hljs-comment">//     jsMemoryRange: [ 2438996, 2768636 ]</span>
    <span class="hljs-comment">//   },</span>
    <span class="hljs-comment">//   other: [</span>
    <span class="hljs-comment">//     {</span>
    <span class="hljs-comment">//       jsMemoryEstimate: 135736,</span>
    <span class="hljs-comment">//       jsMemoryRange: [ 135736, 465376 ]</span>
    <span class="hljs-comment">//     }</span>
    <span class="hljs-comment">//   ]</span>
    <span class="hljs-comment">// }</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);
  });</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>vm.runInContext(code, contextifiedObject[, options])</code><span><a class="mark" href="#vmrunincontextcode-contextifiedobject-options" id="vmrunincontextcode-contextifiedobject-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_runincontext_code_contextifiedobject_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v21.7.0, v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</p></td></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The JavaScript code to compile and run.</li>
<li><code>contextifiedObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The <a href="#what-does-it-mean-to-contextify-an-object">contextified</a> object that will be used
as the <code>global</code> when the <code>code</code> is compiled and run.</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>
<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> Specifies the filename used in stack traces produced
by this script. <strong>Default:</strong> <code>'evalmachine.&#x3C;anonymous>'</code>.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the line number offset that is displayed
in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the first-line column number offset that
is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code>, if an <a href="errors.html#class-error"><code>Error</code></a> occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="errors.html#class-error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</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>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <strong>Default:</strong> <code>false</code>.</li>
<li><code>cachedData</code> <a href="buffer.html#class-buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source.</li>
<li><code>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="vm.html#vmconstantsuse_main_context_default_loader" class="type">&#x3C;vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify the how the modules should be loaded during the evaluation
of this script when <code>import()</code> is called. This option is part of the
experimental modules API. We do not recommend using it in a production
environment. For detailed information, see
<a href="#support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
</ul>
</li>
</ul>
<p>The <code>vm.runInContext()</code> method compiles <code>code</code>, runs it within the context of
the <code>contextifiedObject</code>, then returns the result. Running code does not have
access to the local scope. The <code>contextifiedObject</code> object <em>must</em> have been
previously <a href="#what-does-it-mean-to-contextify-an-object">contextified</a> using the <a href="#vmcreatecontextcontextobject-options"><code>vm.createContext()</code></a> method.</p>
<p>If <code>options</code> is a string, then it specifies the filename.</p>
<p>The following example compiles and executes different scripts using a single
<a href="#what-does-it-mean-to-contextify-an-object">contextified</a> object:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> contextObject = { <span class="hljs-attr">globalVar</span>: <span class="hljs-number">1</span> };
vm.<span class="hljs-title function_">createContext</span>(contextObject);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">10</span>; ++i) {
  vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalVar *= 2;'</span>, contextObject);
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contextObject);
<span class="hljs-comment">// Prints: { globalVar: 1024 }</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>vm.runInNewContext(code[, contextObject[, options]])</code><span><a class="mark" href="#vmruninnewcontextcode-contextobject-options" id="vmruninnewcontextcode-contextobject-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_runinnewcontext_code_contextobject_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v22.8.0</td>
<td><p>The <code>contextObject</code> argument now accepts <code>vm.constants.DONT_CONTEXTIFY</code>.</p></td></tr>
<tr><td>v21.7.0, v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</p></td></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
<tr><td>v14.6.0</td>
<td><p>The <code>microtaskMode</code> option is supported now.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>contextCodeGeneration</code> option is supported now.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The JavaScript code to compile and run.</li>
<li><code>contextObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="vm.html#vmconstantsdont_contextify" class="type">&#x3C;vm.constants.DONT_CONTEXTIFY></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a>
Either <a href="#vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a> or an object that will be <a href="#what-does-it-mean-to-contextify-an-object">contextified</a>.
If <code>undefined</code>, an empty contextified object will be created for backwards compatibility.</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>
<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> Specifies the filename used in stack traces produced
by this script. <strong>Default:</strong> <code>'evalmachine.&#x3C;anonymous>'</code>.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the line number offset that is displayed
in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the first-line column number offset that
is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code>, if an <a href="errors.html#class-error"><code>Error</code></a> occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="errors.html#class-error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</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>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <strong>Default:</strong> <code>false</code>.</li>
<li><code>contextName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Human-readable name of the newly created context.
<strong>Default:</strong> <code>'VM Context i'</code>, where <code>i</code> is an ascending numerical index of
the created context.</li>
<li><code>contextOrigin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <a href="https://developer.mozilla.org/en-US/docs/Glossary/Origin">Origin</a> corresponding to the newly
created context for display purposes. The origin should be formatted like a
URL, but with only the scheme, host, and port (if necessary), like the
value of the <a href="url.html#urlorigin"><code>url.origin</code></a> property of a <a href="url.html#class-url"><code>URL</code></a> object. Most notably,
this string should omit the trailing slash, as that denotes a path.
<strong>Default:</strong> <code>''</code>.</li>
<li><code>contextCodeGeneration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>strings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If set to false any calls to <code>eval</code> or function
constructors (<code>Function</code>, <code>GeneratorFunction</code>, etc) will throw an
<code>EvalError</code>. <strong>Default:</strong> <code>true</code>.</li>
<li><code>wasm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If set to false any attempt to compile a WebAssembly
module will throw a <code>WebAssembly.CompileError</code>. <strong>Default:</strong> <code>true</code>.</li>
</ul>
</li>
<li><code>cachedData</code> <a href="buffer.html#class-buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source.</li>
<li><code>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="vm.html#vmconstantsuse_main_context_default_loader" class="type">&#x3C;vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify the how the modules should be loaded during the evaluation
of this script when <code>import()</code> is called. This option is part of the
experimental modules API. We do not recommend using it in a production
environment. For detailed information, see
<a href="#support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
<li><code>microtaskMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> If set to <code>afterEvaluate</code>, microtasks (tasks
scheduled through <code>Promise</code>s and <code>async function</code>s) will be run immediately
after the script has run. They are included in the <code>timeout</code> and
<code>breakOnSigint</code> scopes in that case.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> the result of the very last statement executed in the script.</li>
</ul>
<p>This method is a shortcut to
<code>(new vm.Script(code, options)).runInContext(vm.createContext(options), options)</code>.
If <code>options</code> is a string, then it specifies the filename.</p>
<p>It does several things at once:</p>
<ol>
<li>Creates a new context.</li>
<li>If <code>contextObject</code> is an object, <a href="#what-does-it-mean-to-contextify-an-object">contextifies</a> it with the new context.
If  <code>contextObject</code> is undefined, creates a new object and <a href="#what-does-it-mean-to-contextify-an-object">contextifies</a> it.
If <code>contextObject</code> is <a href="#vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a>, don't <a href="#what-does-it-mean-to-contextify-an-object">contextify</a> anything.</li>
<li>Compiles the code as a<code>vm.Script</code></li>
<li>Runs the compield code within the created context. The code does not have access to the scope in
which this method is called.</li>
<li>Returns the result.</li>
</ol>
<p>The following example compiles and executes code that increments a global
variable and sets a new one. These globals are contained in the <code>contextObject</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> contextObject = {
  <span class="hljs-attr">animal</span>: <span class="hljs-string">'cat'</span>,
  <span class="hljs-attr">count</span>: <span class="hljs-number">2</span>,
};

vm.<span class="hljs-title function_">runInNewContext</span>(<span class="hljs-string">'count += 1; name = "kitty"'</span>, contextObject);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contextObject);
<span class="hljs-comment">// Prints: { animal: 'cat', count: 3, name: 'kitty' }</span>

<span class="hljs-comment">// This would throw if the context is created from a contextified object.</span>
<span class="hljs-comment">// vm.constants.DONT_CONTEXTIFY allows creating contexts with ordinary global objects that</span>
<span class="hljs-comment">// can be frozen.</span>
<span class="hljs-keyword">const</span> frozenContext = vm.<span class="hljs-title function_">runInNewContext</span>(<span class="hljs-string">'Object.freeze(globalThis); globalThis;'</span>, vm.<span class="hljs-property">constants</span>.<span class="hljs-property">DONT_CONTEXTIFY</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>vm.runInThisContext(code[, options])</code><span><a class="mark" href="#vmruninthiscontextcode-options" id="vmruninthiscontextcode-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_runinthiscontext_code_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v21.7.0, v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</p></td></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The JavaScript code to compile and run.</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>
<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> Specifies the filename used in stack traces produced
by this script. <strong>Default:</strong> <code>'evalmachine.&#x3C;anonymous>'</code>.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the line number offset that is displayed
in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the first-line column number offset that
is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code>, if an <a href="errors.html#class-error"><code>Error</code></a> occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="errors.html#class-error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</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>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <strong>Default:</strong> <code>false</code>.</li>
<li><code>cachedData</code> <a href="buffer.html#class-buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source.</li>
<li><code>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="vm.html#vmconstantsuse_main_context_default_loader" class="type">&#x3C;vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify the how the modules should be loaded during the evaluation
of this script when <code>import()</code> is called. This option is part of the
experimental modules API. We do not recommend using it in a production
environment. For detailed information, see
<a href="#support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> the result of the very last statement executed in the script.</li>
</ul>
<p><code>vm.runInThisContext()</code> compiles <code>code</code>, runs it within the context of the
current <code>global</code> and returns the result. Running code does not have access to
local scope, but does have access to the current <code>global</code> object.</p>
<p>If <code>options</code> is a string, then it specifies the filename.</p>
<p>The following example illustrates using both <code>vm.runInThisContext()</code> and
the JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval"><code>eval()</code></a> function to run the same code:</p>
<!-- eslint-disable prefer-const -->
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">let</span> localVar = <span class="hljs-string">'initial value'</span>;

<span class="hljs-keyword">const</span> vmResult = vm.<span class="hljs-title function_">runInThisContext</span>(<span class="hljs-string">'localVar = "vm";'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`vmResult: '<span class="hljs-subst">${vmResult}</span>', localVar: '<span class="hljs-subst">${localVar}</span>'`</span>);
<span class="hljs-comment">// Prints: vmResult: 'vm', localVar: 'initial value'</span>

<span class="hljs-keyword">const</span> evalResult = <span class="hljs-built_in">eval</span>(<span class="hljs-string">'localVar = "eval";'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`evalResult: '<span class="hljs-subst">${evalResult}</span>', localVar: '<span class="hljs-subst">${localVar}</span>'`</span>);
<span class="hljs-comment">// Prints: evalResult: 'eval', localVar: 'eval'</span></code> <button class="copy-button">copy</button></pre>
<p>Because <code>vm.runInThisContext()</code> does not have access to the local scope,
<code>localVar</code> is unchanged. In contrast, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval"><code>eval()</code></a> <em>does</em> have access to the
local scope, so the value <code>localVar</code> is changed. In this way
<code>vm.runInThisContext()</code> is much like an <a href="https://es5.github.io/#x10.4.2">indirect <code>eval()</code> call</a>, e.g.
<code>(0,eval)('code')</code>.</p>
</section><section><h3>Example: Running an HTTP server within a VM<span><a class="mark" href="#example-running-an-http-server-within-a-vm" id="example-running-an-http-server-within-a-vm">#</a></span><a aria-hidden="true" class="legacy" id="vm_example_running_an_http_server_within_a_vm"></a></h3>
<p>When using either <a href="#scriptruninthiscontextoptions"><code>script.runInThisContext()</code></a> or
<a href="#vmruninthiscontextcode-options"><code>vm.runInThisContext()</code></a>, the code is executed within the current V8 global
context. The code passed to this VM context will have its own isolated scope.</p>
<p>In order to run a simple web server using the <code>node:http</code> module the code passed
to the context must either call <code>require('node:http')</code> on its own, or have a
reference to the <code>node:http</code> module passed to it. For instance:</p>
<pre><code class="language-js"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> code = <span class="hljs-string">`
((require) => {
  const http = require('node:http');

  http.createServer((request, response) => {
    response.writeHead(200, { 'Content-Type': 'text/plain' });
    response.end('Hello World\\n');
  }).listen(8124);

  console.log('Server running at http://127.0.0.1:8124/');
})`</span>;

vm.<span class="hljs-title function_">runInThisContext</span>(code)(<span class="hljs-built_in">require</span>);</code> <button class="copy-button">copy</button></pre>
<p>The <code>require()</code> in the above case shares the state with the context it is
passed from. This may introduce risks when untrusted code is executed, e.g.
altering objects in the context in unwanted ways.</p>
</section><section><h3>What does it mean to "contextify" an object?<span><a class="mark" href="#what-does-it-mean-to-contextify-an-object" id="what-does-it-mean-to-contextify-an-object">#</a></span><a aria-hidden="true" class="legacy" id="vm_what_does_it_mean_to_contextify_an_object"></a></h3>
<p>All JavaScript executed within Node.js runs within the scope of a "context".
According to the <a href="https://v8.dev/docs/embed#contexts">V8 Embedder's Guide</a>:</p>
<blockquote>
<p>In V8, a context is an execution environment that allows separate, unrelated,
JavaScript applications to run in a single instance of V8. You must explicitly
specify the context in which you want any JavaScript code to be run.</p>
</blockquote>
<p>When the method <code>vm.createContext()</code> is called with an object, the <code>contextObject</code> argument
will be used to wrap the global object of a new instance of a V8 Context
(if <code>contextObject</code> is <code>undefined</code>, a new object will be created from the current context
before its contextified). This V8 Context provides the <code>code</code> run using the <code>node:vm</code>
module's methods with an isolated global environment within which it can operate.
The process of creating the V8 Context and associating it with the <code>contextObject</code>
in the outer context is what this document refers to as "contextifying" the object.</p>
<p>The contextifying would introduce some quirks to the <code>globalThis</code> value in the context.
For example, it cannot be frozen, and it is not reference equal to the <code>contextObject</code>
in the outer context.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-comment">// An undefined `contextObject` option makes the global object contextified.</span>
<span class="hljs-keyword">const</span> context = vm.<span class="hljs-title function_">createContext</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalThis'</span>, context) === context);  <span class="hljs-comment">// false</span>
<span class="hljs-comment">// A contextified global object cannot be frozen.</span>
<span class="hljs-keyword">try</span> {
  vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'Object.freeze(globalThis);'</span>, context);
} <span class="hljs-keyword">catch</span> (e) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(e); <span class="hljs-comment">// TypeError: Cannot freeze</span>
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalThis.foo = 1; foo;'</span>, context));  <span class="hljs-comment">// 1</span></code> <button class="copy-button">copy</button></pre>
<p>To create a context with an ordinary global object and get access to a global proxy in
the outer context with fewer quirks, specify <code>vm.constants.DONT_CONTEXTIFY</code> as the
<code>contextObject</code> argument.</p>
<h4><code>vm.constants.DONT_CONTEXTIFY</code><span><a class="mark" href="#vmconstantsdont_contextify" id="vmconstantsdont_contextify">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_constants_dont_contextify"></a></h4>
<p>This constant, when used as the <code>contextObject</code> argument in vm APIs, instructs Node.js to create
a context without wrapping its global object with another object in a Node.js-specific manner.
As a result, the <code>globalThis</code> value inside the new context would behave more closely to an ordinary
one.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-comment">// Use vm.constants.DONT_CONTEXTIFY to freeze the global object.</span>
<span class="hljs-keyword">const</span> context = vm.<span class="hljs-title function_">createContext</span>(vm.<span class="hljs-property">constants</span>.<span class="hljs-property">DONT_CONTEXTIFY</span>);
vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'Object.freeze(globalThis);'</span>, context);
<span class="hljs-keyword">try</span> {
  vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'bar = 1; bar;'</span>, context);
} <span class="hljs-keyword">catch</span> (e) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(e); <span class="hljs-comment">// Uncaught ReferenceError: bar is not defined</span>
}</code> <button class="copy-button">copy</button></pre>
<p>When <code>vm.constants.DONT_CONTEXTIFY</code> is used as the <code>contextObject</code> argument to <a href="#vmcreatecontextcontextobject-options"><code>vm.createContext()</code></a>,
the returned object is a proxy-like object to the global object in the newly created context with
fewer Node.js-specific quirks. It is reference equal to the <code>globalThis</code> value in the new context,
can be modified from outside the context, and can be used to access built-ins in the new context directly.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> context = vm.<span class="hljs-title function_">createContext</span>(vm.<span class="hljs-property">constants</span>.<span class="hljs-property">DONT_CONTEXTIFY</span>);

<span class="hljs-comment">// Returned object is reference equal to globalThis in the new context.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalThis'</span>, context) === context);  <span class="hljs-comment">// true</span>

<span class="hljs-comment">// Can be used to access globals in the new context directly.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">Array</span>);  <span class="hljs-comment">// [Function: Array]</span>
vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'foo = 1;'</span>, context);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">foo</span>);  <span class="hljs-comment">// 1</span>
context.<span class="hljs-property">bar</span> = <span class="hljs-number">1</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'bar;'</span>, context));  <span class="hljs-comment">// 1</span>

<span class="hljs-comment">// Can be frozen and it affects the inner context.</span>
<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">freeze</span>(context);
<span class="hljs-keyword">try</span> {
  vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'baz = 1; baz;'</span>, context);
} <span class="hljs-keyword">catch</span> (e) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(e); <span class="hljs-comment">// Uncaught ReferenceError: baz is not defined</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Timeout interactions with asynchronous tasks and Promises<span><a class="mark" href="#timeout-interactions-with-asynchronous-tasks-and-promises" id="timeout-interactions-with-asynchronous-tasks-and-promises">#</a></span><a aria-hidden="true" class="legacy" id="vm_timeout_interactions_with_asynchronous_tasks_and_promises"></a></h3>
<p><code>Promise</code>s and <code>async function</code>s can schedule tasks run by the JavaScript
engine asynchronously. By default, these tasks are run after all JavaScript
functions on the current stack are done executing.
This allows escaping the functionality of the <code>timeout</code> and
<code>breakOnSigint</code> options.</p>
<p>For example, the following code executed by <code>vm.runInNewContext()</code> with a
timeout of 5 milliseconds schedules an infinite loop to run after a promise
resolves. The scheduled loop is never interrupted by the timeout:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">loop</span>(<span class="hljs-params"></span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'entering loop'</span>);
  <span class="hljs-keyword">while</span> (<span class="hljs-number">1</span>) <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>());
}

vm.<span class="hljs-title function_">runInNewContext</span>(
  <span class="hljs-string">'Promise.resolve().then(() => loop());'</span>,
  { loop, <span class="hljs-variable language_">console</span> },
  { <span class="hljs-attr">timeout</span>: <span class="hljs-number">5</span> },
);
<span class="hljs-comment">// This is printed *before* 'entering loop' (!)</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done executing'</span>);</code> <button class="copy-button">copy</button></pre>
<p>This can be addressed by passing <code>microtaskMode: 'afterEvaluate'</code> to the code
that creates the <code>Context</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">loop</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">while</span> (<span class="hljs-number">1</span>) <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>());
}

vm.<span class="hljs-title function_">runInNewContext</span>(
  <span class="hljs-string">'Promise.resolve().then(() => loop());'</span>,
  { loop, <span class="hljs-variable language_">console</span> },
  { <span class="hljs-attr">timeout</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">microtaskMode</span>: <span class="hljs-string">'afterEvaluate'</span> },
);</code> <button class="copy-button">copy</button></pre>
<p>In this case, the microtask scheduled through <code>promise.then()</code> will be run
before returning from <code>vm.runInNewContext()</code>, and will be interrupted
by the <code>timeout</code> functionality. This applies only to code running in a
<code>vm.Context</code>, so e.g. <a href="#vmruninthiscontextcode-options"><code>vm.runInThisContext()</code></a> does not take this option.</p>
<p>Promise callbacks are entered into the microtask queue of the context in which
they were created. For example, if <code>() => loop()</code> is replaced with just <code>loop</code>
in the above example, then <code>loop</code> will be pushed into the global microtask
queue, because it is a function from the outer (main) context, and thus will
also be able to escape the timeout.</p>
<p>If asynchronous scheduling functions such as <code>process.nextTick()</code>,
<code>queueMicrotask()</code>, <code>setTimeout()</code>, <code>setImmediate()</code>, etc. are made available
inside a <code>vm.Context</code>, functions passed to them will be added to global queues,
which are shared by all contexts. Therefore, callbacks passed to those functions
are not controllable through the timeout either.</p>
</section><section><h3>Support of dynamic <code>import()</code> in compilation APIs<span><a class="mark" href="#support-of-dynamic-import-in-compilation-apis" id="support-of-dynamic-import-in-compilation-apis">#</a></span><a aria-hidden="true" class="legacy" id="vm_support_of_dynamic_import_in_compilation_apis"></a></h3>
<p>The following APIs support an <code>importModuleDynamically</code> option to enable dynamic
<code>import()</code> in code compiled by the vm module.</p>
<ul>
<li><code>new vm.Script</code></li>
<li><code>vm.compileFunction()</code></li>
<li><code>new vm.SourceTextModule</code></li>
<li><code>vm.runInThisContext()</code></li>
<li><code>vm.runInContext()</code></li>
<li><code>vm.runInNewContext()</code></li>
<li><code>vm.createContext()</code></li>
</ul>
<p>This option is still part of the experimental modules API. We do not recommend
using it in a production environment.</p>
<h4>When the <code>importModuleDynamically</code> option is not specified or undefined<span><a class="mark" href="#when-the-importmoduledynamically-option-is-not-specified-or-undefined" id="when-the-importmoduledynamically-option-is-not-specified-or-undefined">#</a></span><a aria-hidden="true" class="legacy" id="vm_when_the_importmoduledynamically_option_is_not_specified_or_undefined"></a></h4>
<p>If this option is not specified, or if it's <code>undefined</code>, code containing
<code>import()</code> can still be compiled by the vm APIs, but when the compiled code is
executed and it actually calls <code>import()</code>, the result will reject with
<a href="errors.html#err_vm_dynamic_import_callback_missing"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code></a>.</p>
<h4>When <code>importModuleDynamically</code> is <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code><span><a class="mark" href="#when-importmoduledynamically-is-vmconstantsuse_main_context_default_loader" id="when-importmoduledynamically-is-vmconstantsuse_main_context_default_loader">#</a></span><a aria-hidden="true" class="legacy" id="vm_when_importmoduledynamically_is_vm_constants_use_main_context_default_loader"></a></h4>
<p>This option is currently not supported for <code>vm.SourceTextModule</code>.</p>
<p>With this option, when an <code>import()</code> is initiated in the compiled code, Node.js
would use the default ESM loader from the main context to load the requested
module and return it to the code being executed.</p>
<p>This gives access to Node.js built-in modules such as <code>fs</code> or <code>http</code>
to the code being compiled. If the code is executed in a different context,
be aware that the objects created by modules loaded from the main context
are still from the main context and not <code>instanceof</code> built-in classes in the
new context.</p>

<pre class="with-49-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Script</span>, constants } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(
  <span class="hljs-string">'import("node:fs").then(({readFile}) => readFile instanceof Function)'</span>,
  { <span class="hljs-attr">importModuleDynamically</span>: constants.<span class="hljs-property">USE_MAIN_CONTEXT_DEFAULT_LOADER</span> });

<span class="hljs-comment">// false: URL loaded from the main context is not an instance of the Function</span>
<span class="hljs-comment">// class in the new context.</span>
script.<span class="hljs-title function_">runInNewContext</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Script</span>, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(
  <span class="hljs-string">'import("node:fs").then(({readFile}) => readFile instanceof Function)'</span>,
  { <span class="hljs-attr">importModuleDynamically</span>: constants.<span class="hljs-property">USE_MAIN_CONTEXT_DEFAULT_LOADER</span> });

<span class="hljs-comment">// false: URL loaded from the main context is not an instance of the Function</span>
<span class="hljs-comment">// class in the new context.</span>
script.<span class="hljs-title function_">runInNewContext</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><button class="copy-button">copy</button></pre>
<p>This option also allows the script or function to load user modules:</p>

<pre class="with-49-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_">Script</span>, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;
<span class="hljs-keyword">import</span> { resolve } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;
<span class="hljs-keyword">import</span> { writeFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-comment">// Write test.js and test.txt to the directory where the current script</span>
<span class="hljs-comment">// being run is located.</span>
<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-title function_">resolve</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">dirname</span>, <span class="hljs-string">'test.mjs'</span>),
              <span class="hljs-string">'export const filename = "./test.json";'</span>);
<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-title function_">resolve</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">dirname</span>, <span class="hljs-string">'test.json'</span>),
              <span class="hljs-string">'{"hello": "world"}'</span>);

<span class="hljs-comment">// Compile a script that loads test.mjs and then test.json</span>
<span class="hljs-comment">// as if the script is placed in the same directory.</span>
<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(
  <span class="hljs-string">`(async function() {
    const { filename } = await import('./test.mjs');
    return import(filename, { with: { type: 'json' } })
  })();`</span>,
  {
    <span class="hljs-attr">filename</span>: <span class="hljs-title function_">resolve</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">dirname</span>, <span class="hljs-string">'test-with-default.js'</span>),
    <span class="hljs-attr">importModuleDynamically</span>: constants.<span class="hljs-property">USE_MAIN_CONTEXT_DEFAULT_LOADER</span>,
  });

<span class="hljs-comment">// { default: { hello: 'world' } }</span>
script.<span class="hljs-title function_">runInThisContext</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Script</span>, constants } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> { resolve } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);
<span class="hljs-keyword">const</span> { writeFileSync } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-comment">// Write test.js and test.txt to the directory where the current script</span>
<span class="hljs-comment">// being run is located.</span>
<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-title function_">resolve</span>(__dirname, <span class="hljs-string">'test.mjs'</span>),
              <span class="hljs-string">'export const filename = "./test.json";'</span>);
<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-title function_">resolve</span>(__dirname, <span class="hljs-string">'test.json'</span>),
              <span class="hljs-string">'{"hello": "world"}'</span>);

<span class="hljs-comment">// Compile a script that loads test.mjs and then test.json</span>
<span class="hljs-comment">// as if the script is placed in the same directory.</span>
<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(
  <span class="hljs-string">`(async function() {
    const { filename } = await import('./test.mjs');
    return import(filename, { with: { type: 'json' } })
  })();`</span>,
  {
    <span class="hljs-attr">filename</span>: <span class="hljs-title function_">resolve</span>(__dirname, <span class="hljs-string">'test-with-default.js'</span>),
    <span class="hljs-attr">importModuleDynamically</span>: constants.<span class="hljs-property">USE_MAIN_CONTEXT_DEFAULT_LOADER</span>,
  });

<span class="hljs-comment">// { default: { hello: 'world' } }</span>
script.<span class="hljs-title function_">runInThisContext</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><button class="copy-button">copy</button></pre>
<p>There are a few caveats with loading user modules using the default loader
from the main context:</p>
<ol>
<li>The module being resolved would be relative to the <code>filename</code> option passed
to <code>vm.Script</code> or <code>vm.compileFunction()</code>. The resolution can work with a
<code>filename</code> that's either an absolute path or a URL string.  If <code>filename</code> is
a string that's neither an absolute path or a URL, or if it's undefined,
the resolution will be relative to the current working directory
of the process. In the case of <code>vm.createContext()</code>, the resolution is always
relative to the current working directory since this option is only used when
there isn't a referrer script or module.</li>
<li>For any given <code>filename</code> that resolves to a specific path, once the process
manages to load a particular module from that path, the result may be cached,
and subsequent load of the same module from the same path would return the
same thing. If the <code>filename</code> is a URL string, the cache would not be hit
if it has different search parameters. For <code>filename</code>s that are not URL
strings, there is currently no way to bypass the caching behavior.</li>
</ol>
<h4>When <code>importModuleDynamically</code> is a function<span><a class="mark" href="#when-importmoduledynamically-is-a-function" id="when-importmoduledynamically-is-a-function">#</a></span><a aria-hidden="true" class="legacy" id="vm_when_importmoduledynamically_is_a_function"></a></h4>
<p>When <code>importModuleDynamically</code> is a function, it will be invoked when <code>import()</code>
is called in the compiled code for users to customize how the requested module
should be compiled and evaluated. Currently, the Node.js instance must be
launched with the <code>--experimental-vm-modules</code> flag for this option to work. If
the flag isn't set, this callback will be ignored. If the code evaluated
actually calls to <code>import()</code>, the result will reject with
<a href="errors.html#err_vm_dynamic_import_callback_missing_flag"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG</code></a>.</p>
<p>The callback <code>importModuleDynamically(specifier, referrer, importAttributes)</code>
has the following signature:</p>
<ul>
<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> specifier passed to <code>import()</code></li>
<li><code>referrer</code> <a href="vm.html#class-vmscript" class="type">&#x3C;vm.Script></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="vm.html#class-vmsourcetextmodule" class="type">&#x3C;vm.SourceTextModule></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
The referrer is the compiled <code>vm.Script</code> for <code>new vm.Script</code>,
<code>vm.runInThisContext</code>, <code>vm.runInContext</code> and <code>vm.runInNewContext</code>. It's the
compiled <code>Function</code> for <code>vm.compileFunction</code>, the compiled
<code>vm.SourceTextModule</code> for <code>new vm.SourceTextModule</code>, and the context <code>Object</code>
for <code>vm.createContext()</code>.</li>
<li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The <code>"with"</code> value passed to the
<a href="https://tc39.es/proposal-import-attributes/#sec-evaluate-import-call"><code>optionsExpression</code></a> optional parameter, or an empty object if no value was
provided.</li>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects" class="type">&#x3C;Module Namespace Object></a> | <a href="vm.html#class-vmmodule" class="type">&#x3C;vm.Module></a> Returning a <code>vm.Module</code> is
recommended in order to take advantage of error tracking, and to avoid issues
with namespaces that contain <code>then</code> function exports.</li>
</ul>

<pre class="with-58-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// This script must be run with --experimental-vm-modules.</span>
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Script</span>, <span class="hljs-title class_">SyntheticModule</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(<span class="hljs-string">'import("foo.json", { with: { type: "json" } })'</span>, {
  <span class="hljs-keyword">async</span> <span class="hljs-title function_">importModuleDynamically</span>(<span class="hljs-params">specifier, referrer, importAttributes</span>) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(specifier);  <span class="hljs-comment">// 'foo.json'</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(referrer);   <span class="hljs-comment">// The compiled script</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(importAttributes);  <span class="hljs-comment">// { type: 'json' }</span>
    <span class="hljs-keyword">const</span> m = <span class="hljs-keyword">new</span> <span class="hljs-title class_">SyntheticModule</span>([<span class="hljs-string">'bar'</span>], <span class="hljs-function">() =></span> { });
    <span class="hljs-keyword">await</span> m.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> { });
    m.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'bar'</span>, { <span class="hljs-attr">hello</span>: <span class="hljs-string">'world'</span> });
    <span class="hljs-keyword">return</span> m;
  },
});
<span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> script.<span class="hljs-title function_">runInThisContext</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);  <span class="hljs-comment">//  { bar: { hello: 'world' } }</span></code><code class="language-js cjs"><span class="hljs-comment">// This script must be run with --experimental-vm-modules.</span>
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Script</span>, <span class="hljs-title class_">SyntheticModule</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">main</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(<span class="hljs-string">'import("foo.json", { with: { type: "json" } })'</span>, {
    <span class="hljs-keyword">async</span> <span class="hljs-title function_">importModuleDynamically</span>(<span class="hljs-params">specifier, referrer, importAttributes</span>) {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(specifier);  <span class="hljs-comment">// 'foo.json'</span>
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(referrer);   <span class="hljs-comment">// The compiled script</span>
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(importAttributes);  <span class="hljs-comment">// { type: 'json' }</span>
      <span class="hljs-keyword">const</span> m = <span class="hljs-keyword">new</span> <span class="hljs-title class_">SyntheticModule</span>([<span class="hljs-string">'bar'</span>], <span class="hljs-function">() =></span> { });
      <span class="hljs-keyword">await</span> m.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> { });
      m.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'bar'</span>, { <span class="hljs-attr">hello</span>: <span class="hljs-string">'world'</span> });
      <span class="hljs-keyword">return</span> m;
    },
  });
  <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> script.<span class="hljs-title function_">runInThisContext</span>();
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);  <span class="hljs-comment">//  { bar: { hello: 'world' } }</span>
})();</code><button class="copy-button">copy</button></pre></section>
        <!-- API END -->
      </div>
    </div>
  </div>
</body>
</html>