• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1<!DOCTYPE html>
2<html lang="en">
3<head>
4  <meta charset="utf-8">
5  <meta name="viewport" content="width=device-width">
6  <meta name="nodejs.org:node-version" content="v18.20.1">
7  <title>VM (executing JavaScript) | Node.js v18.20.1 Documentation</title>
8  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback">
9  <link rel="stylesheet" href="assets/style.css">
10  <link rel="stylesheet" href="assets/hljs.css">
11  <link rel="canonical" href="https://nodejs.org/api/vm.html">
12  <script async defer src="assets/api.js" type="text/javascript"></script>
13  <style>@media(max-width:462px){.with-30-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}@media(max-width:702px){.with-60-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}</style>
14</head>
15<body class="alt apidoc" id="api-section-vm">
16  <div id="content" class="clearfix">
17    <div id="column2" class="interior">
18      <div id="intro" class="interior">
19        <a href="/" title="Go back to the home page">
20          Node.js
21        </a>
22      </div>
23      <ul>
24<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
25<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
26</ul>
27<hr class="line">
28<ul>
29<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
30<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li>
31<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
32<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
33<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
34<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
35<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
36<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
37<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
38<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
39<li><a href="console.html" class="nav-console">Console</a></li>
40<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
41<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
42<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
43<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
44<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
45<li><a href="dns.html" class="nav-dns">DNS</a></li>
46<li><a href="domain.html" class="nav-domain">Domain</a></li>
47<li><a href="errors.html" class="nav-errors">Errors</a></li>
48<li><a href="events.html" class="nav-events">Events</a></li>
49<li><a href="fs.html" class="nav-fs">File system</a></li>
50<li><a href="globals.html" class="nav-globals">Globals</a></li>
51<li><a href="http.html" class="nav-http">HTTP</a></li>
52<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
53<li><a href="https.html" class="nav-https">HTTPS</a></li>
54<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
55<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
56<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
57<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
58<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li>
59<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
60<li><a href="net.html" class="nav-net">Net</a></li>
61<li><a href="os.html" class="nav-os">OS</a></li>
62<li><a href="path.html" class="nav-path">Path</a></li>
63<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
64<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
65<li><a href="process.html" class="nav-process">Process</a></li>
66<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
67<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
68<li><a href="readline.html" class="nav-readline">Readline</a></li>
69<li><a href="repl.html" class="nav-repl">REPL</a></li>
70<li><a href="report.html" class="nav-report">Report</a></li>
71<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
72<li><a href="stream.html" class="nav-stream">Stream</a></li>
73<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
74<li><a href="test.html" class="nav-test">Test runner</a></li>
75<li><a href="timers.html" class="nav-timers">Timers</a></li>
76<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
77<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
78<li><a href="tty.html" class="nav-tty">TTY</a></li>
79<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
80<li><a href="url.html" class="nav-url">URL</a></li>
81<li><a href="util.html" class="nav-util">Utilities</a></li>
82<li><a href="v8.html" class="nav-v8">V8</a></li>
83<li><a href="vm.html" class="nav-vm active">VM</a></li>
84<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
85<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
86<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
87<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
88<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
89</ul>
90<hr class="line">
91<ul>
92<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
93</ul>
94    </div>
95
96    <div id="column1" data-id="vm" class="interior">
97      <header class="header">
98        <div class="header-container">
99          <h1>Node.js v18.20.1 documentation</h1>
100          <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden>
101            <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24">
102              <path fill="none" d="M0 0h24v24H0z" />
103              <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"/>
104              <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"/>
105            </svg>
106            <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24">
107              <path d="M0 0h24v24H0z" fill="none" />
108              <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"/>
109            </svg>
110          </button>
111        </div>
112        <div id="gtoc">
113          <ul>
114            <li class="pinned-header">Node.js v18.20.1</li>
115
116    <li class="picker-header">
117      <a href="#">
118        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
119        Table of contents
120      </a>
121
122      <div class="picker"><div class="toc"><ul>
123<li><span class="stability_2"><a href="#vm-executing-javascript">VM (executing JavaScript)</a></span>
124<ul>
125<li><a href="#class-vmscript">Class: <code>vm.Script</code></a>
126<ul>
127<li><a href="#new-vmscriptcode-options"><code>new vm.Script(code[, options])</code></a></li>
128<li><a href="#scriptcacheddatarejected"><code>script.cachedDataRejected</code></a></li>
129<li><a href="#scriptcreatecacheddata"><code>script.createCachedData()</code></a></li>
130<li><a href="#scriptrunincontextcontextifiedobject-options"><code>script.runInContext(contextifiedObject[, options])</code></a></li>
131<li><a href="#scriptruninnewcontextcontextobject-options"><code>script.runInNewContext([contextObject[, options]])</code></a></li>
132<li><a href="#scriptruninthiscontextoptions"><code>script.runInThisContext([options])</code></a></li>
133<li><a href="#scriptsourcemapurl"><code>script.sourceMapURL</code></a></li>
134</ul>
135</li>
136<li><span class="stability_1"><a href="#class-vmmodule">Class: <code>vm.Module</code></a></span>
137<ul>
138<li><a href="#moduledependencyspecifiers"><code>module.dependencySpecifiers</code></a></li>
139<li><a href="#moduleerror"><code>module.error</code></a></li>
140<li><a href="#moduleevaluateoptions"><code>module.evaluate([options])</code></a></li>
141<li><a href="#moduleidentifier"><code>module.identifier</code></a></li>
142<li><a href="#modulelinklinker"><code>module.link(linker)</code></a></li>
143<li><a href="#modulenamespace"><code>module.namespace</code></a></li>
144<li><a href="#modulestatus"><code>module.status</code></a></li>
145</ul>
146</li>
147<li><span class="stability_1"><a href="#class-vmsourcetextmodule">Class: <code>vm.SourceTextModule</code></a></span>
148<ul>
149<li><a href="#new-vmsourcetextmodulecode-options"><code>new vm.SourceTextModule(code[, options])</code></a></li>
150<li><a href="#sourcetextmodulecreatecacheddata"><code>sourceTextModule.createCachedData()</code></a></li>
151</ul>
152</li>
153<li><span class="stability_1"><a href="#class-vmsyntheticmodule">Class: <code>vm.SyntheticModule</code></a></span>
154<ul>
155<li><a href="#new-vmsyntheticmoduleexportnames-evaluatecallback-options"><code>new vm.SyntheticModule(exportNames, evaluateCallback[, options])</code></a></li>
156<li><a href="#syntheticmodulesetexportname-value"><code>syntheticModule.setExport(name, value)</code></a></li>
157</ul>
158</li>
159<li><a href="#vmcompilefunctioncode-params-options"><code>vm.compileFunction(code[, params[, options]])</code></a></li>
160<li><a href="#vmcreatecontextcontextobject-options"><code>vm.createContext([contextObject[, options]])</code></a></li>
161<li><a href="#vmiscontextobject"><code>vm.isContext(object)</code></a></li>
162<li><span class="stability_1"><a href="#vmmeasurememoryoptions"><code>vm.measureMemory([options])</code></a></span></li>
163<li><a href="#vmrunincontextcode-contextifiedobject-options"><code>vm.runInContext(code, contextifiedObject[, options])</code></a></li>
164<li><a href="#vmruninnewcontextcode-contextobject-options"><code>vm.runInNewContext(code[, contextObject[, options]])</code></a></li>
165<li><a href="#vmruninthiscontextcode-options"><code>vm.runInThisContext(code[, options])</code></a></li>
166<li><a href="#example-running-an-http-server-within-a-vm">Example: Running an HTTP server within a VM</a></li>
167<li><a href="#what-does-it-mean-to-contextify-an-object">What does it mean to "contextify" an object?</a></li>
168<li><a href="#timeout-interactions-with-asynchronous-tasks-and-promises">Timeout interactions with asynchronous tasks and Promises</a></li>
169</ul>
170</li>
171</ul></div></div>
172    </li>
173
174
175    <li class="picker-header">
176      <a href="#">
177        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
178        Index
179      </a>
180
181      <div class="picker"><ul>
182<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
183<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
184
185      <li>
186        <a href="index.html">Index</a>
187      </li>
188    </ul>
189
190<hr class="line">
191<ul>
192<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
193<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li>
194<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
195<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
196<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
197<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
198<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
199<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
200<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
201<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
202<li><a href="console.html" class="nav-console">Console</a></li>
203<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
204<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
205<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
206<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
207<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
208<li><a href="dns.html" class="nav-dns">DNS</a></li>
209<li><a href="domain.html" class="nav-domain">Domain</a></li>
210<li><a href="errors.html" class="nav-errors">Errors</a></li>
211<li><a href="events.html" class="nav-events">Events</a></li>
212<li><a href="fs.html" class="nav-fs">File system</a></li>
213<li><a href="globals.html" class="nav-globals">Globals</a></li>
214<li><a href="http.html" class="nav-http">HTTP</a></li>
215<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
216<li><a href="https.html" class="nav-https">HTTPS</a></li>
217<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
218<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
219<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
220<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
221<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li>
222<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
223<li><a href="net.html" class="nav-net">Net</a></li>
224<li><a href="os.html" class="nav-os">OS</a></li>
225<li><a href="path.html" class="nav-path">Path</a></li>
226<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
227<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
228<li><a href="process.html" class="nav-process">Process</a></li>
229<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
230<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
231<li><a href="readline.html" class="nav-readline">Readline</a></li>
232<li><a href="repl.html" class="nav-repl">REPL</a></li>
233<li><a href="report.html" class="nav-report">Report</a></li>
234<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
235<li><a href="stream.html" class="nav-stream">Stream</a></li>
236<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
237<li><a href="test.html" class="nav-test">Test runner</a></li>
238<li><a href="timers.html" class="nav-timers">Timers</a></li>
239<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
240<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
241<li><a href="tty.html" class="nav-tty">TTY</a></li>
242<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
243<li><a href="url.html" class="nav-url">URL</a></li>
244<li><a href="util.html" class="nav-util">Utilities</a></li>
245<li><a href="v8.html" class="nav-v8">V8</a></li>
246<li><a href="vm.html" class="nav-vm active">VM</a></li>
247<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
248<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
249<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
250<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
251<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
252</ul>
253<hr class="line">
254<ul>
255<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
256</ul></div>
257    </li>
258
259
260    <li class="picker-header">
261      <a href="#">
262        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
263        Other versions
264      </a>
265      <div class="picker"><ol id="alt-docs"><li><a href="https://nodejs.org/docs/latest-v21.x/api/vm.html">21.x</a></li>
266<li><a href="https://nodejs.org/docs/latest-v20.x/api/vm.html">20.x <b>LTS</b></a></li>
267<li><a href="https://nodejs.org/docs/latest-v19.x/api/vm.html">19.x</a></li>
268<li><a href="https://nodejs.org/docs/latest-v18.x/api/vm.html">18.x <b>LTS</b></a></li>
269<li><a href="https://nodejs.org/docs/latest-v17.x/api/vm.html">17.x</a></li>
270<li><a href="https://nodejs.org/docs/latest-v16.x/api/vm.html">16.x</a></li>
271<li><a href="https://nodejs.org/docs/latest-v15.x/api/vm.html">15.x</a></li>
272<li><a href="https://nodejs.org/docs/latest-v14.x/api/vm.html">14.x</a></li>
273<li><a href="https://nodejs.org/docs/latest-v13.x/api/vm.html">13.x</a></li>
274<li><a href="https://nodejs.org/docs/latest-v12.x/api/vm.html">12.x</a></li>
275<li><a href="https://nodejs.org/docs/latest-v11.x/api/vm.html">11.x</a></li>
276<li><a href="https://nodejs.org/docs/latest-v10.x/api/vm.html">10.x</a></li>
277<li><a href="https://nodejs.org/docs/latest-v9.x/api/vm.html">9.x</a></li>
278<li><a href="https://nodejs.org/docs/latest-v8.x/api/vm.html">8.x</a></li>
279<li><a href="https://nodejs.org/docs/latest-v7.x/api/vm.html">7.x</a></li>
280<li><a href="https://nodejs.org/docs/latest-v6.x/api/vm.html">6.x</a></li>
281<li><a href="https://nodejs.org/docs/latest-v5.x/api/vm.html">5.x</a></li>
282<li><a href="https://nodejs.org/docs/latest-v4.x/api/vm.html">4.x</a></li>
283<li><a href="https://nodejs.org/docs/latest-v0.12.x/api/vm.html">0.12.x</a></li>
284<li><a href="https://nodejs.org/docs/latest-v0.10.x/api/vm.html">0.10.x</a></li></ol></div>
285    </li>
286
287            <li class="picker-header">
288              <a href="#">
289                <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
290                Options
291              </a>
292
293              <div class="picker">
294                <ul>
295                  <li>
296                    <a href="all.html">View on single page</a>
297                  </li>
298                  <li>
299                    <a href="vm.json">View as JSON</a>
300                  </li>
301                  <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/main/doc/api/vm.md">Edit on GitHub</a></li>
302                </ul>
303              </div>
304            </li>
305          </ul>
306        </div>
307        <hr>
308      </header>
309
310      <details id="toc" open><summary>Table of contents</summary><ul>
311<li><span class="stability_2"><a href="#vm-executing-javascript">VM (executing JavaScript)</a></span>
312<ul>
313<li><a href="#class-vmscript">Class: <code>vm.Script</code></a>
314<ul>
315<li><a href="#new-vmscriptcode-options"><code>new vm.Script(code[, options])</code></a></li>
316<li><a href="#scriptcacheddatarejected"><code>script.cachedDataRejected</code></a></li>
317<li><a href="#scriptcreatecacheddata"><code>script.createCachedData()</code></a></li>
318<li><a href="#scriptrunincontextcontextifiedobject-options"><code>script.runInContext(contextifiedObject[, options])</code></a></li>
319<li><a href="#scriptruninnewcontextcontextobject-options"><code>script.runInNewContext([contextObject[, options]])</code></a></li>
320<li><a href="#scriptruninthiscontextoptions"><code>script.runInThisContext([options])</code></a></li>
321<li><a href="#scriptsourcemapurl"><code>script.sourceMapURL</code></a></li>
322</ul>
323</li>
324<li><span class="stability_1"><a href="#class-vmmodule">Class: <code>vm.Module</code></a></span>
325<ul>
326<li><a href="#moduledependencyspecifiers"><code>module.dependencySpecifiers</code></a></li>
327<li><a href="#moduleerror"><code>module.error</code></a></li>
328<li><a href="#moduleevaluateoptions"><code>module.evaluate([options])</code></a></li>
329<li><a href="#moduleidentifier"><code>module.identifier</code></a></li>
330<li><a href="#modulelinklinker"><code>module.link(linker)</code></a></li>
331<li><a href="#modulenamespace"><code>module.namespace</code></a></li>
332<li><a href="#modulestatus"><code>module.status</code></a></li>
333</ul>
334</li>
335<li><span class="stability_1"><a href="#class-vmsourcetextmodule">Class: <code>vm.SourceTextModule</code></a></span>
336<ul>
337<li><a href="#new-vmsourcetextmodulecode-options"><code>new vm.SourceTextModule(code[, options])</code></a></li>
338<li><a href="#sourcetextmodulecreatecacheddata"><code>sourceTextModule.createCachedData()</code></a></li>
339</ul>
340</li>
341<li><span class="stability_1"><a href="#class-vmsyntheticmodule">Class: <code>vm.SyntheticModule</code></a></span>
342<ul>
343<li><a href="#new-vmsyntheticmoduleexportnames-evaluatecallback-options"><code>new vm.SyntheticModule(exportNames, evaluateCallback[, options])</code></a></li>
344<li><a href="#syntheticmodulesetexportname-value"><code>syntheticModule.setExport(name, value)</code></a></li>
345</ul>
346</li>
347<li><a href="#vmcompilefunctioncode-params-options"><code>vm.compileFunction(code[, params[, options]])</code></a></li>
348<li><a href="#vmcreatecontextcontextobject-options"><code>vm.createContext([contextObject[, options]])</code></a></li>
349<li><a href="#vmiscontextobject"><code>vm.isContext(object)</code></a></li>
350<li><span class="stability_1"><a href="#vmmeasurememoryoptions"><code>vm.measureMemory([options])</code></a></span></li>
351<li><a href="#vmrunincontextcode-contextifiedobject-options"><code>vm.runInContext(code, contextifiedObject[, options])</code></a></li>
352<li><a href="#vmruninnewcontextcode-contextobject-options"><code>vm.runInNewContext(code[, contextObject[, options]])</code></a></li>
353<li><a href="#vmruninthiscontextcode-options"><code>vm.runInThisContext(code[, options])</code></a></li>
354<li><a href="#example-running-an-http-server-within-a-vm">Example: Running an HTTP server within a VM</a></li>
355<li><a href="#what-does-it-mean-to-contextify-an-object">What does it mean to "contextify" an object?</a></li>
356<li><a href="#timeout-interactions-with-asynchronous-tasks-and-promises">Timeout interactions with asynchronous tasks and Promises</a></li>
357</ul>
358</li>
359</ul></details>
360
361      <div id="apicontent">
362        <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>
363
364<p></p><div class="api_stability api_stability_2"><a href="documentation.html#stability-index">Stability: 2</a> - Stable</div><p></p>
365
366<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v18.20.1/lib/vm.js">lib/vm.js</a></p>
367<p>The <code>node:vm</code> module enables compiling and running code within V8 Virtual
368Machine contexts.</p>
369<p><strong class="critical">The <code>node:vm</code> module is not a security
370mechanism. Do not use it to run untrusted code.</strong></p>
371<p>JavaScript code can be compiled and run immediately or
372compiled, saved, and run later.</p>
373<p>A common use case is to run the code in a different V8 Context. This means
374invoked code has a different global object than the invoking code.</p>
375<p>One can provide the context by <a href="#what-does-it-mean-to-contextify-an-object"><em>contextifying</em></a> an
376object. The invoked code treats any property in the context like a
377global variable. Any changes to global variables caused by the invoked
378code are reflected in the context object.</p>
379<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>);
380
381<span class="hljs-keyword">const</span> x = <span class="hljs-number">1</span>;
382
383<span class="hljs-keyword">const</span> context = { <span class="hljs-attr">x</span>: <span class="hljs-number">2</span> };
384vm.<span class="hljs-title function_">createContext</span>(context); <span class="hljs-comment">// Contextify the object.</span>
385
386<span class="hljs-keyword">const</span> code = <span class="hljs-string">'x += 40; var y = 17;'</span>;
387<span class="hljs-comment">// `x` and `y` are global variables in the context.</span>
388<span class="hljs-comment">// Initially, x has the value 2 because that is the value of context.x.</span>
389vm.<span class="hljs-title function_">runInContext</span>(code, context);
390
391<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>
392<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>
393
394<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>
395<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>
396<div class="api_metadata">
397<span>Added in: v0.3.1</span>
398</div>
399<p>Instances of the <code>vm.Script</code> class contain precompiled scripts that can be
400executed in specific contexts.</p>
401<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>
402<div class="api_metadata">
403<details class="changelog"><summary>History</summary>
404<table>
405<tbody><tr><th>Version</th><th>Changes</th></tr>
406<tr><td>v17.0.0, v16.12.0</td>
407<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
408<tr><td>v10.6.0</td>
409<td><p>The <code>produceCachedData</code> is deprecated in favour of <code>script.createCachedData()</code>.</p></td></tr>
410<tr><td>v5.7.0</td>
411<td><p>The <code>cachedData</code> and <code>produceCachedData</code> options are supported now.</p></td></tr>
412<tr><td>v0.3.1</td>
413<td><p><span>Added in: v0.3.1</span></p></td></tr>
414</tbody></table>
415</details>
416</div>
417<ul>
418<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>
419<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>
420<ul>
421<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
422by this script. <strong>Default:</strong> <code>'evalmachine.&#x3C;anonymous>'</code>.</li>
423<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
424in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
425<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
426is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
427<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
428<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
429source. When supplied, the <code>cachedDataRejected</code> value will be set to
430either <code>true</code> or <code>false</code> depending on acceptance of the data by V8.</li>
431<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
432will attempt to produce code cache data for <code>code</code>. Upon success, a
433<code>Buffer</code> with V8's code cache data will be produced and stored in the
434<code>cachedData</code> property of the returned <code>vm.Script</code> instance.
435The <code>cachedDataProduced</code> value will be set to either <code>true</code> or <code>false</code>
436depending on whether code cache data is produced successfully.
437This option is <strong>deprecated</strong> in favor of <code>script.createCachedData()</code>.
438<strong>Default:</strong> <code>false</code>.</li>
439<li><code>importModuleDynamically</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 module
440when <code>import()</code> is called. If this option is not specified, calls to
441<code>import()</code> will reject with <a href="errors.html#err_vm_dynamic_import_callback_missing"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code></a>.
442This option is part of the experimental modules API. We do not recommend
443using it in a production environment. If <code>--experimental-vm-modules</code> isn't
444set, this callback will be ignored and calls to <code>import()</code> will reject with
445<a href="errors.html#err_vm_dynamic_import_callback_missing_flag"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG</code></a>.
446<ul>
447<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>
448<li><code>script</code> <a href="vm.html#class-vmscript" class="type">&#x3C;vm.Script></a></li>
449<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
450<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
451was provided.</li>
452<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
453recommended in order to take advantage of error tracking, and to avoid
454issues with namespaces that contain <code>then</code> function exports.</li>
455</ul>
456</li>
457</ul>
458</li>
459</ul>
460<p>If <code>options</code> is a string, then it specifies the filename.</p>
461<p>Creating a new <code>vm.Script</code> object compiles <code>code</code> but does not run it. The
462compiled <code>vm.Script</code> can be run later multiple times. The <code>code</code> is not bound to
463any global object; rather, it is bound before each run, just for that run.</p>
464<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>
465<div class="api_metadata">
466<span>Added in: v5.7.0</span>
467</div>
468<ul>
469<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>
470</ul>
471<p>When <code>cachedData</code> is supplied to create the <code>vm.Script</code>, this value will be set
472to either <code>true</code> or <code>false</code> depending on acceptance of the data by V8.
473Otherwise the value is <code>undefined</code>.</p>
474<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>
475<div class="api_metadata">
476<span>Added in: v10.6.0</span>
477</div>
478<ul>
479<li>Returns: <a href="buffer.html#class-buffer" class="type">&#x3C;Buffer></a></li>
480</ul>
481<p>Creates a code cache that can be used with the <code>Script</code> constructor's
482<code>cachedData</code> option. Returns a <code>Buffer</code>. This method may be called at any
483time and any number of times.</p>
484<p>The code cache of the <code>Script</code> doesn't contain any JavaScript observable
485states. The code cache is safe to be saved along side the script source and
486used to construct new <code>Script</code> instances multiple times.</p>
487<p>Functions in the <code>Script</code> source can be marked as lazily compiled and they are
488not compiled at construction of the <code>Script</code>. These functions are going to be
489compiled when they are invoked the first time. The code cache serializes the
490metadata that V8 currently knows about the <code>Script</code> that it can use to speed up
491future compilations.</p>
492<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">`
493function add(a, b) {
494  return a + b;
495}
496
497const x = add(1, 2);
498`</span>);
499
500<span class="hljs-keyword">const</span> cacheWithoutAdd = script.<span class="hljs-title function_">createCachedData</span>();
501<span class="hljs-comment">// In `cacheWithoutAdd` the function `add()` is marked for full compilation</span>
502<span class="hljs-comment">// upon invocation.</span>
503
504script.<span class="hljs-title function_">runInThisContext</span>();
505
506<span class="hljs-keyword">const</span> cacheWithAdd = script.<span class="hljs-title function_">createCachedData</span>();
507<span class="hljs-comment">// `cacheWithAdd` contains fully compiled function `add()`.</span></code> <button class="copy-button">copy</button></pre>
508<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>
509<div class="api_metadata">
510<details class="changelog"><summary>History</summary>
511<table>
512<tbody><tr><th>Version</th><th>Changes</th></tr>
513<tr><td>v6.3.0</td>
514<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
515<tr><td>v0.3.1</td>
516<td><p><span>Added in: v0.3.1</span></p></td></tr>
517</tbody></table>
518</details>
519</div>
520<ul>
521<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
522<code>vm.createContext()</code> method.</li>
523<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
524<ul>
525<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
526while compiling the <code>code</code>, the line of code causing the error is attached
527to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
528<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>
529before terminating execution. If execution is terminated, an <a href="errors.html#class-error"><code>Error</code></a>
530will be thrown. This value must be a strictly positive integer.</li>
531<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>
532(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
533<a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
534<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
535work after that. <strong>Default:</strong> <code>false</code>.</li>
536</ul>
537</li>
538<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>
539</ul>
540<p>Runs the compiled code contained by the <code>vm.Script</code> object within the given
541<code>contextifiedObject</code> and returns the result. Running code does not have access
542to local scope.</p>
543<p>The following example compiles code that increments a global variable, sets
544the value of another global variable, then execute the code multiple times.
545The globals are contained in the <code>context</code> object.</p>
546<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>);
547
548<span class="hljs-keyword">const</span> context = {
549  <span class="hljs-attr">animal</span>: <span class="hljs-string">'cat'</span>,
550  <span class="hljs-attr">count</span>: <span class="hljs-number">2</span>,
551};
552
553<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>);
554
555vm.<span class="hljs-title function_">createContext</span>(context);
556<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) {
557  script.<span class="hljs-title function_">runInContext</span>(context);
558}
559
560<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context);
561<span class="hljs-comment">// Prints: { animal: 'cat', count: 12, name: 'kitty' }</span></code> <button class="copy-button">copy</button></pre>
562<p>Using the <code>timeout</code> or <code>breakOnSigint</code> options will result in new event loops
563and corresponding threads being started, which have a non-zero performance
564overhead.</p>
565<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>
566<div class="api_metadata">
567<details class="changelog"><summary>History</summary>
568<table>
569<tbody><tr><th>Version</th><th>Changes</th></tr>
570<tr><td>v14.6.0</td>
571<td><p>The <code>microtaskMode</code> option is supported now.</p></td></tr>
572<tr><td>v10.0.0</td>
573<td><p>The <code>contextCodeGeneration</code> option is supported now.</p></td></tr>
574<tr><td>v6.3.0</td>
575<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
576<tr><td>v0.3.1</td>
577<td><p><span>Added in: v0.3.1</span></p></td></tr>
578</tbody></table>
579</details>
580</div>
581<ul>
582<li><code>contextObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> An object that will be <a href="#what-does-it-mean-to-contextify-an-object">contextified</a>. If
583<code>undefined</code>, a new object will be created.</li>
584<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
585<ul>
586<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
587while compiling the <code>code</code>, the line of code causing the error is attached
588to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
589<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>
590before terminating execution. If execution is terminated, an <a href="errors.html#class-error"><code>Error</code></a>
591will be thrown. This value must be a strictly positive integer.</li>
592<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>
593(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
594<a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
595<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
596work after that. <strong>Default:</strong> <code>false</code>.</li>
597<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.
598<strong>Default:</strong> <code>'VM Context i'</code>, where <code>i</code> is an ascending numerical index of
599the created context.</li>
600<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
601created context for display purposes. The origin should be formatted like a
602URL, but with only the scheme, host, and port (if necessary), like the
603value 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,
604this string should omit the trailing slash, as that denotes a path.
605<strong>Default:</strong> <code>''</code>.</li>
606<li><code>contextCodeGeneration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
607<ul>
608<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
609constructors (<code>Function</code>, <code>GeneratorFunction</code>, etc) will throw an
610<code>EvalError</code>. <strong>Default:</strong> <code>true</code>.</li>
611<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
612module will throw a <code>WebAssembly.CompileError</code>. <strong>Default:</strong> <code>true</code>.</li>
613</ul>
614</li>
615<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
616scheduled through <code>Promise</code>s and <code>async function</code>s) will be run immediately
617after the script has run. They are included in the <code>timeout</code> and
618<code>breakOnSigint</code> scopes in that case.</li>
619</ul>
620</li>
621<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>
622</ul>
623<p>First contextifies the given <code>contextObject</code>, runs the compiled code contained
624by the <code>vm.Script</code> object within the created context, and returns the result.
625Running code does not have access to local scope.</p>
626<p>The following example compiles code that sets a global variable, then executes
627the code multiple times in different contexts. The globals are set on and
628contained within each individual <code>context</code>.</p>
629<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>);
630
631<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>);
632
633<span class="hljs-keyword">const</span> contexts = [{}, {}, {}];
634contexts.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
635  script.<span class="hljs-title function_">runInNewContext</span>(context);
636});
637
638<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contexts);
639<span class="hljs-comment">// Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]</span></code> <button class="copy-button">copy</button></pre>
640<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>
641<div class="api_metadata">
642<details class="changelog"><summary>History</summary>
643<table>
644<tbody><tr><th>Version</th><th>Changes</th></tr>
645<tr><td>v6.3.0</td>
646<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
647<tr><td>v0.3.1</td>
648<td><p><span>Added in: v0.3.1</span></p></td></tr>
649</tbody></table>
650</details>
651</div>
652<ul>
653<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
654<ul>
655<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
656while compiling the <code>code</code>, the line of code causing the error is attached
657to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
658<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>
659before terminating execution. If execution is terminated, an <a href="errors.html#class-error"><code>Error</code></a>
660will be thrown. This value must be a strictly positive integer.</li>
661<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>
662(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
663<a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
664<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
665work after that. <strong>Default:</strong> <code>false</code>.</li>
666</ul>
667</li>
668<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>
669</ul>
670<p>Runs the compiled code contained by the <code>vm.Script</code> within the context of the
671current <code>global</code> object. Running code does not have access to local scope, but
672<em>does</em> have access to the current <code>global</code> object.</p>
673<p>The following example compiles code that increments a <code>global</code> variable then
674executes that code multiple times:</p>
675<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>);
676
677<span class="hljs-variable language_">global</span>.<span class="hljs-property">globalVar</span> = <span class="hljs-number">0</span>;
678
679<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> });
680
681<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) {
682  script.<span class="hljs-title function_">runInThisContext</span>();
683}
684
685<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(globalVar);
686
687<span class="hljs-comment">// 1000</span></code> <button class="copy-button">copy</button></pre>
688<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>
689<div class="api_metadata">
690<span>Added in: v18.13.0</span>
691</div>
692<ul>
693<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>
694</ul>
695<p>When the script is compiled from a source that contains a source map magic
696comment, this property will be set to the URL of the source map.</p>
697
698<pre class="with-30-chars"><input class="js-flavor-selector" 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>;
699
700<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">`
701function myFunc() {}
702//# sourceMappingURL=sourcemap.json
703`</span>);
704
705<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(script.<span class="hljs-property">sourceMapURL</span>);
706<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>);
707
708<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">`
709function myFunc() {}
710//# sourceMappingURL=sourcemap.json
711`</span>);
712
713<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(script.<span class="hljs-property">sourceMapURL</span>);
714<span class="hljs-comment">// Prints: sourcemap.json</span></code><button class="copy-button">copy</button></pre>
715</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>
716<div class="api_metadata">
717<span>Added in: v13.0.0, v12.16.0</span>
718</div>
719<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
720<p>This feature is only available with the <code>--experimental-vm-modules</code> command
721flag enabled.</p>
722<p>The <code>vm.Module</code> class provides a low-level interface for using
723ECMAScript modules in VM contexts. It is the counterpart of the <code>vm.Script</code>
724class that closely mirrors <a href="https://www.ecma-international.org/ecma-262/#sec-abstract-module-records">Module Record</a>s as defined in the ECMAScript
725specification.</p>
726<p>Unlike <code>vm.Script</code> however, every <code>vm.Module</code> object is bound to a context from
727its creation. Operations on <code>vm.Module</code> objects are intrinsically asynchronous,
728in contrast with the synchronous nature of <code>vm.Script</code> objects. The use of
729'async' functions can help with manipulating <code>vm.Module</code> objects.</p>
730<p>Using a <code>vm.Module</code> object requires three distinct steps: creation/parsing,
731linking, and evaluation. These three steps are illustrated in the following
732example.</p>
733<p>This implementation lies at a lower level than the <a href="esm.html#modules-ecmascript-modules">ECMAScript Module
734loader</a>. There is also no way to interact with the Loader yet, though
735support is planned.</p>
736
737<pre class="with-30-chars"><input class="js-flavor-selector" 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>;
738
739<span class="hljs-keyword">const</span> contextifiedObject = vm.<span class="hljs-title function_">createContext</span>({
740  <span class="hljs-attr">secret</span>: <span class="hljs-number">42</span>,
741  <span class="hljs-attr">print</span>: <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>,
742});
743
744<span class="hljs-comment">// Step 1</span>
745<span class="hljs-comment">//</span>
746<span class="hljs-comment">// Create a Module by constructing a new `vm.SourceTextModule` object. This</span>
747<span class="hljs-comment">// parses the provided source text, throwing a `SyntaxError` if anything goes</span>
748<span class="hljs-comment">// wrong. By default, a Module is created in the top context. But here, we</span>
749<span class="hljs-comment">// specify `contextifiedObject` as the context this Module belongs to.</span>
750<span class="hljs-comment">//</span>
751<span class="hljs-comment">// Here, we attempt to obtain the default export from the module "foo", and</span>
752<span class="hljs-comment">// put it into local binding "secret".</span>
753
754<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">`
755  import s from 'foo';
756  s;
757  print(s);
758`</span>, { <span class="hljs-attr">context</span>: contextifiedObject });
759
760<span class="hljs-comment">// Step 2</span>
761<span class="hljs-comment">//</span>
762<span class="hljs-comment">// "Link" the imported dependencies of this Module to it.</span>
763<span class="hljs-comment">//</span>
764<span class="hljs-comment">// The provided linking callback (the "linker") accepts two arguments: the</span>
765<span class="hljs-comment">// parent module (`bar` in this case) and the string that is the specifier of</span>
766<span class="hljs-comment">// the imported module. The callback is expected to return a Module that</span>
767<span class="hljs-comment">// corresponds to the provided specifier, with certain requirements documented</span>
768<span class="hljs-comment">// in `module.link()`.</span>
769<span class="hljs-comment">//</span>
770<span class="hljs-comment">// If linking has not started for the returned Module, the same linker</span>
771<span class="hljs-comment">// callback will be called on the returned Module.</span>
772<span class="hljs-comment">//</span>
773<span class="hljs-comment">// Even top-level Modules without dependencies must be explicitly linked. The</span>
774<span class="hljs-comment">// callback provided would never be called, however.</span>
775<span class="hljs-comment">//</span>
776<span class="hljs-comment">// The link() method returns a Promise that will be resolved when all the</span>
777<span class="hljs-comment">// Promises returned by the linker resolve.</span>
778<span class="hljs-comment">//</span>
779<span class="hljs-comment">// Note: This is a contrived example in that the linker function creates a new</span>
780<span class="hljs-comment">// "foo" module every time it is called. In a full-fledged module system, a</span>
781<span class="hljs-comment">// cache would probably be used to avoid duplicated modules.</span>
782
783<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>) {
784  <span class="hljs-keyword">if</span> (specifier === <span class="hljs-string">'foo'</span>) {
785    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">`
786      // The "secret" variable refers to the global variable we added to
787      // "contextifiedObject" when creating the context.
788      export default secret;
789    `</span>, { <span class="hljs-attr">context</span>: referencingModule.<span class="hljs-property">context</span> });
790
791    <span class="hljs-comment">// Using `contextifiedObject` instead of `referencingModule.context`</span>
792    <span class="hljs-comment">// here would work as well.</span>
793  }
794  <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>);
795}
796<span class="hljs-keyword">await</span> bar.<span class="hljs-title function_">link</span>(linker);
797
798<span class="hljs-comment">// Step 3</span>
799<span class="hljs-comment">//</span>
800<span class="hljs-comment">// Evaluate the Module. The evaluate() method returns a promise which will</span>
801<span class="hljs-comment">// resolve after the module has finished evaluating.</span>
802
803<span class="hljs-comment">// Prints 42.</span>
804<span class="hljs-keyword">await</span> bar.evaluate();</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>);
805
806<span class="hljs-keyword">const</span> contextifiedObject = vm.<span class="hljs-title function_">createContext</span>({
807  <span class="hljs-attr">secret</span>: <span class="hljs-number">42</span>,
808  <span class="hljs-attr">print</span>: <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>,
809});
810
811(<span class="hljs-keyword">async</span> () => {
812  <span class="hljs-comment">// Step 1</span>
813  <span class="hljs-comment">//</span>
814  <span class="hljs-comment">// Create a Module by constructing a new `vm.SourceTextModule` object. This</span>
815  <span class="hljs-comment">// parses the provided source text, throwing a `SyntaxError` if anything goes</span>
816  <span class="hljs-comment">// wrong. By default, a Module is created in the top context. But here, we</span>
817  <span class="hljs-comment">// specify `contextifiedObject` as the context this Module belongs to.</span>
818  <span class="hljs-comment">//</span>
819  <span class="hljs-comment">// Here, we attempt to obtain the default export from the module "foo", and</span>
820  <span class="hljs-comment">// put it into local binding "secret".</span>
821
822  <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">`
823    import s from 'foo';
824    s;
825    print(s);
826  `</span>, { <span class="hljs-attr">context</span>: contextifiedObject });
827
828  <span class="hljs-comment">// Step 2</span>
829  <span class="hljs-comment">//</span>
830  <span class="hljs-comment">// "Link" the imported dependencies of this Module to it.</span>
831  <span class="hljs-comment">//</span>
832  <span class="hljs-comment">// The provided linking callback (the "linker") accepts two arguments: the</span>
833  <span class="hljs-comment">// parent module (`bar` in this case) and the string that is the specifier of</span>
834  <span class="hljs-comment">// the imported module. The callback is expected to return a Module that</span>
835  <span class="hljs-comment">// corresponds to the provided specifier, with certain requirements documented</span>
836  <span class="hljs-comment">// in `module.link()`.</span>
837  <span class="hljs-comment">//</span>
838  <span class="hljs-comment">// If linking has not started for the returned Module, the same linker</span>
839  <span class="hljs-comment">// callback will be called on the returned Module.</span>
840  <span class="hljs-comment">//</span>
841  <span class="hljs-comment">// Even top-level Modules without dependencies must be explicitly linked. The</span>
842  <span class="hljs-comment">// callback provided would never be called, however.</span>
843  <span class="hljs-comment">//</span>
844  <span class="hljs-comment">// The link() method returns a Promise that will be resolved when all the</span>
845  <span class="hljs-comment">// Promises returned by the linker resolve.</span>
846  <span class="hljs-comment">//</span>
847  <span class="hljs-comment">// Note: This is a contrived example in that the linker function creates a new</span>
848  <span class="hljs-comment">// "foo" module every time it is called. In a full-fledged module system, a</span>
849  <span class="hljs-comment">// cache would probably be used to avoid duplicated modules.</span>
850
851  <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>) {
852    <span class="hljs-keyword">if</span> (specifier === <span class="hljs-string">'foo'</span>) {
853      <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">`
854        // The "secret" variable refers to the global variable we added to
855        // "contextifiedObject" when creating the context.
856        export default secret;
857      `</span>, { <span class="hljs-attr">context</span>: referencingModule.<span class="hljs-property">context</span> });
858
859      <span class="hljs-comment">// Using `contextifiedObject` instead of `referencingModule.context`</span>
860      <span class="hljs-comment">// here would work as well.</span>
861    }
862    <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>);
863  }
864  <span class="hljs-keyword">await</span> bar.<span class="hljs-title function_">link</span>(linker);
865
866  <span class="hljs-comment">// Step 3</span>
867  <span class="hljs-comment">//</span>
868  <span class="hljs-comment">// Evaluate the Module. The evaluate() method returns a promise which will</span>
869  <span class="hljs-comment">// resolve after the module has finished evaluating.</span>
870
871  <span class="hljs-comment">// Prints 42.</span>
872  <span class="hljs-keyword">await</span> bar.evaluate();
873})();</code><button class="copy-button">copy</button></pre>
874<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>
875<ul>
876<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
877</ul>
878<p>The specifiers of all dependencies of this module. The returned array is frozen
879to disallow any changes to it.</p>
880<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
881the ECMAScript specification.</p>
882<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>
883<ul>
884<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
885</ul>
886<p>If the <code>module.status</code> is <code>'errored'</code>, this property contains the exception
887thrown by the module during evaluation. If the status is anything else,
888accessing this property will result in a thrown exception.</p>
889<p>The value <code>undefined</code> cannot be used for cases where there is not a thrown
890exception due to possible ambiguity with <code>throw undefined;</code>.</p>
891<p>Corresponds to the <code>[[EvaluationError]]</code> field of <a href="https://tc39.es/ecma262/#sec-cyclic-module-records">Cyclic Module Record</a>s
892in the ECMAScript specification.</p>
893<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>
894<ul>
895<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
896<ul>
897<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
898before terminating execution. If execution is interrupted, an <a href="errors.html#class-error"><code>Error</code></a>
899will be thrown. This value must be a strictly positive integer.</li>
900<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>
901(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
902<a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
903<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
904work after that. <strong>Default:</strong> <code>false</code>.</li>
905</ul>
906</li>
907<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>
908</ul>
909<p>Evaluate the module.</p>
910<p>This must be called after the module has been linked; otherwise it will reject.
911It could be called also when the module has already been evaluated, in which
912case it will either do nothing if the initial evaluation ended in success
913(<code>module.status</code> is <code>'evaluated'</code>) or it will re-throw the exception that the
914initial evaluation resulted in (<code>module.status</code> is <code>'errored'</code>).</p>
915<p>This method cannot be called while the module is being evaluated
916(<code>module.status</code> is <code>'evaluating'</code>).</p>
917<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
918Record</a>s in the ECMAScript specification.</p>
919<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>
920<ul>
921<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
922</ul>
923<p>The identifier of the current module, as set in the constructor.</p>
924<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>
925<div class="api_metadata">
926<details class="changelog"><summary>History</summary>
927<table>
928<tbody><tr><th>Version</th><th>Changes</th></tr>
929<tr><td>v18.19.0</td>
930<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>
931</tbody></table>
932</details>
933</div>
934<ul>
935<li><code>linker</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
936<ul>
937<li>
938<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>
939<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>;
940<span class="hljs-comment">//              ^^^^^ the module specifier</span></code> <button class="copy-button">copy</button></pre>
941</li>
942<li>
943<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>
944</li>
945<li>
946<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>
947<ul>
948<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:
949<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> };
950<span class="hljs-comment">//                           ^^^^^^^^^^^^^^^^^ the attribute</span></code> <button class="copy-button">copy</button></pre>
951Per ECMA-262, hosts are expected to trigger an error if an
952unsupported attribute is present.</li>
953<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>
954</ul>
955</li>
956<li>
957<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>
958</li>
959</ul>
960</li>
961<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
962</ul>
963<p>Link module dependencies. This method must be called before evaluation, and
964can only be called once per module.</p>
965<p>The function is expected to return a <code>Module</code> object or a <code>Promise</code> that
966eventually resolves to a <code>Module</code> object. The returned <code>Module</code> must satisfy the
967following two invariants:</p>
968<ul>
969<li>It must belong to the same context as the parent <code>Module</code>.</li>
970<li>Its <code>status</code> must not be <code>'errored'</code>.</li>
971</ul>
972<p>If the returned <code>Module</code>'s <code>status</code> is <code>'unlinked'</code>, this method will be
973recursively called on the returned <code>Module</code> with the same provided <code>linker</code>
974function.</p>
975<p><code>link()</code> returns a <code>Promise</code> that will either get resolved when all linking
976instances resolve to a valid <code>Module</code>, or rejected if the linker function either
977throws an exception or returns an invalid <code>Module</code>.</p>
978<p>The linker function roughly corresponds to the implementation-defined
979<a href="https://tc39.es/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> abstract operation in the ECMAScript
980specification, with a few key differences:</p>
981<ul>
982<li>The linker function is allowed to be asynchronous while
983<a href="https://tc39.es/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> is synchronous.</li>
984</ul>
985<p>The actual <a href="https://tc39.es/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> implementation used during module
986linking is one that returns the modules linked during linking. Since at
987that point all modules would have been fully linked already, the
988<a href="https://tc39.es/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> implementation is fully synchronous per
989specification.</p>
990<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
991Record</a>s in the ECMAScript specification.</p>
992<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>
993<ul>
994<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
995</ul>
996<p>The namespace object of the module. This is only available after linking
997(<code>module.link()</code>) has completed.</p>
998<p>Corresponds to the <a href="https://tc39.es/ecma262/#sec-getmodulenamespace">GetModuleNamespace</a> abstract operation in the ECMAScript
999specification.</p>
1000<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>
1001<ul>
1002<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
1003</ul>
1004<p>The current status of the module. Will be one of:</p>
1005<ul>
1006<li>
1007<p><code>'unlinked'</code>: <code>module.link()</code> has not yet been called.</p>
1008</li>
1009<li>
1010<p><code>'linking'</code>: <code>module.link()</code> has been called, but not all Promises returned
1011by the linker function have been resolved yet.</p>
1012</li>
1013<li>
1014<p><code>'linked'</code>: The module has been linked successfully, and all of its
1015dependencies are linked, but <code>module.evaluate()</code> has not yet been called.</p>
1016</li>
1017<li>
1018<p><code>'evaluating'</code>: The module is being evaluated through a <code>module.evaluate()</code> on
1019itself or a parent module.</p>
1020</li>
1021<li>
1022<p><code>'evaluated'</code>: The module has been successfully evaluated.</p>
1023</li>
1024<li>
1025<p><code>'errored'</code>: The module has been evaluated, but an exception was thrown.</p>
1026</li>
1027</ul>
1028<p>Other than <code>'errored'</code>, this status string corresponds to the specification's
1029<a href="https://tc39.es/ecma262/#sec-cyclic-module-records">Cyclic Module Record</a>'s <code>[[Status]]</code> field. <code>'errored'</code> corresponds to
1030<code>'evaluated'</code> in the specification, but with <code>[[EvaluationError]]</code> set to a
1031value that is not <code>undefined</code>.</p>
1032</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>
1033<div class="api_metadata">
1034<span>Added in: v9.6.0</span>
1035</div>
1036<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
1037<p>This feature is only available with the <code>--experimental-vm-modules</code> command
1038flag enabled.</p>
1039<ul>
1040<li>Extends: <a href="vm.html#class-vmmodule" class="type">&#x3C;vm.Module></a></li>
1041</ul>
1042<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
1043defined in the ECMAScript specification.</p>
1044<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>
1045<div class="api_metadata">
1046<details class="changelog"><summary>History</summary>
1047<table>
1048<tbody><tr><th>Version</th><th>Changes</th></tr>
1049<tr><td>v17.0.0, v16.12.0</td>
1050<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
1051</tbody></table>
1052</details>
1053</div>
1054<ul>
1055<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>
1056<li><code>options</code>
1057<ul>
1058<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.
1059<strong>Default:</strong> <code>'vm:module(i)'</code> where <code>i</code> is a context-specific ascending
1060index.</li>
1061<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
1062<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
1063source. The <code>code</code> must be the same as the module from which this
1064<code>cachedData</code> was created.</li>
1065<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
1066<code>vm.createContext()</code> method, to compile and evaluate this <code>Module</code> in.
1067If no context is specified, the module is evaluated in the current
1068execution context.</li>
1069<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
1070in stack traces produced by this <code>Module</code>. <strong>Default:</strong> <code>0</code>.</li>
1071<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
1072is displayed in stack traces produced by this <code>Module</code>. <strong>Default:</strong> <code>0</code>.</li>
1073<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>
1074to initialize the <code>import.meta</code>.
1075<ul>
1076<li><code>meta</code> <a href="esm.html#importmeta" class="type">&#x3C;import.meta></a></li>
1077<li><code>module</code> <a href="vm.html#class-vmsourcetextmodule" class="type">&#x3C;vm.SourceTextModule></a></li>
1078</ul>
1079</li>
1080<li><code>importModuleDynamically</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 module
1081when <code>import()</code> is called. If this option is not specified, calls to
1082<code>import()</code> will reject with <a href="errors.html#err_vm_dynamic_import_callback_missing"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code></a>.
1083If <code>--experimental-vm-modules</code> isn't set, this callback will be ignored
1084and calls to <code>import()</code> will reject with
1085<a href="errors.html#err_vm_dynamic_import_callback_missing_flag"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG</code></a>.
1086<ul>
1087<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>
1088<li><code>module</code> <a href="vm.html#class-vmmodule" class="type">&#x3C;vm.Module></a></li>
1089<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>"assert"</code> value passed to the
1090<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
1091was provided.</li>
1092<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
1093recommended in order to take advantage of error tracking, and to avoid
1094issues with namespaces that contain <code>then</code> function exports.</li>
1095</ul>
1096</li>
1097</ul>
1098</li>
1099</ul>
1100<p>Creates a new <code>SourceTextModule</code> instance.</p>
1101<p>Properties assigned to the <code>import.meta</code> object that are objects may
1102allow the module to access information outside the specified <code>context</code>. Use
1103<code>vm.runInContext()</code> to create objects in a specific context.</p>
1104
1105<pre class="with-60-chars"><input class="js-flavor-selector" 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>;
1106
1107<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> });
1108
1109<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>(
1110  <span class="hljs-string">'Object.getPrototypeOf(import.meta.prop).secret = secret;'</span>,
1111  {
1112    <span class="hljs-title function_">initializeImportMeta</span>(<span class="hljs-params">meta</span>) {
1113      <span class="hljs-comment">// Note: this object is created in the top context. As such,</span>
1114      <span class="hljs-comment">// Object.getPrototypeOf(import.meta.prop) points to the</span>
1115      <span class="hljs-comment">// Object.prototype in the top context rather than that in</span>
1116      <span class="hljs-comment">// the contextified object.</span>
1117      meta.<span class="hljs-property">prop</span> = {};
1118    },
1119  });
1120<span class="hljs-comment">// Since module has no dependencies, the linker function will never be called.</span>
1121<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> {});
1122<span class="hljs-keyword">await</span> <span class="hljs-variable language_">module</span>.evaluate();
1123
1124<span class="hljs-comment">// Now, Object.prototype.secret will be equal to 42.</span>
1125<span class="hljs-comment">//</span>
1126<span class="hljs-comment">// To fix this problem, replace</span>
1127<span class="hljs-comment">//     meta.prop = {};</span>
1128<span class="hljs-comment">// above with</span>
1129<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>);
1130<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> });
1131(<span class="hljs-keyword">async</span> () => {
1132  <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>(
1133    <span class="hljs-string">'Object.getPrototypeOf(import.meta.prop).secret = secret;'</span>,
1134    {
1135      <span class="hljs-title function_">initializeImportMeta</span>(<span class="hljs-params">meta</span>) {
1136        <span class="hljs-comment">// Note: this object is created in the top context. As such,</span>
1137        <span class="hljs-comment">// Object.getPrototypeOf(import.meta.prop) points to the</span>
1138        <span class="hljs-comment">// Object.prototype in the top context rather than that in</span>
1139        <span class="hljs-comment">// the contextified object.</span>
1140        meta.<span class="hljs-property">prop</span> = {};
1141      },
1142    });
1143  <span class="hljs-comment">// Since module has no dependencies, the linker function will never be called.</span>
1144  <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> {});
1145  <span class="hljs-keyword">await</span> <span class="hljs-variable language_">module</span>.evaluate();
1146  <span class="hljs-comment">// Now, Object.prototype.secret will be equal to 42.</span>
1147  <span class="hljs-comment">//</span>
1148  <span class="hljs-comment">// To fix this problem, replace</span>
1149  <span class="hljs-comment">//     meta.prop = {};</span>
1150  <span class="hljs-comment">// above with</span>
1151  <span class="hljs-comment">//     meta.prop = vm.runInContext('{}', contextifiedObject);</span>
1152})();</code><button class="copy-button">copy</button></pre>
1153<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>
1154<div class="api_metadata">
1155<span>Added in: v13.7.0, v12.17.0</span>
1156</div>
1157<ul>
1158<li>Returns: <a href="buffer.html#class-buffer" class="type">&#x3C;Buffer></a></li>
1159</ul>
1160<p>Creates a code cache that can be used with the <code>SourceTextModule</code> constructor's
1161<code>cachedData</code> option. Returns a <code>Buffer</code>. This method may be called any number
1162of times before the module has been evaluated.</p>
1163<p>The code cache of the <code>SourceTextModule</code> doesn't contain any JavaScript
1164observable states. The code cache is safe to be saved along side the script
1165source and used to construct new <code>SourceTextModule</code> instances multiple times.</p>
1166<p>Functions in the <code>SourceTextModule</code> source can be marked as lazily compiled
1167and they are not compiled at construction of the <code>SourceTextModule</code>. These
1168functions are going to be compiled when they are invoked the first time. The
1169code cache serializes the metadata that V8 currently knows about the
1170<code>SourceTextModule</code> that it can use to speed up future compilations.</p>
1171<pre><code class="language-js"><span class="hljs-comment">// Create an initial module</span>
1172<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>);
1173
1174<span class="hljs-comment">// Create cached data from this module</span>
1175<span class="hljs-keyword">const</span> cachedData = <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">createCachedData</span>();
1176
1177<span class="hljs-comment">// Create a new module using the cached data. The code must be the same.</span>
1178<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>
1179</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>
1180<div class="api_metadata">
1181<span>Added in: v13.0.0, v12.16.0</span>
1182</div>
1183<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
1184<p>This feature is only available with the <code>--experimental-vm-modules</code> command
1185flag enabled.</p>
1186<ul>
1187<li>Extends: <a href="vm.html#class-vmmodule" class="type">&#x3C;vm.Module></a></li>
1188</ul>
1189<p>The <code>vm.SyntheticModule</code> class provides the <a href="https://heycam.github.io/webidl/#synthetic-module-records">Synthetic Module Record</a> as
1190defined in the WebIDL specification. The purpose of synthetic modules is to
1191provide a generic interface for exposing non-JavaScript sources to ECMAScript
1192module graphs.</p>
1193<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>);
1194
1195<span class="hljs-keyword">const</span> source = <span class="hljs-string">'{ "a": 1 }'</span>;
1196<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>) {
1197  <span class="hljs-keyword">const</span> obj = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(source);
1198  <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'default'</span>, obj);
1199});
1200
1201<span class="hljs-comment">// Use `module` in linking...</span></code> <button class="copy-button">copy</button></pre>
1202<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>
1203<div class="api_metadata">
1204<span>Added in: v13.0.0, v12.16.0</span>
1205</div>
1206<ul>
1207<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
1208module.</li>
1209<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>
1210<li><code>options</code>
1211<ul>
1212<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.
1213<strong>Default:</strong> <code>'vm:module(i)'</code> where <code>i</code> is a context-specific ascending
1214index.</li>
1215<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
1216<code>vm.createContext()</code> method, to compile and evaluate this <code>Module</code> in.</li>
1217</ul>
1218</li>
1219</ul>
1220<p>Creates a new <code>SyntheticModule</code> instance.</p>
1221<p>Objects assigned to the exports of this instance may allow importers of
1222the module to access information outside the specified <code>context</code>. Use
1223<code>vm.runInContext()</code> to create objects in a specific context.</p>
1224<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>
1225<div class="api_metadata">
1226<span>Added in: v13.0.0, v12.16.0</span>
1227</div>
1228<ul>
1229<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>
1230<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>
1231</ul>
1232<p>This method is used after the module is linked to set the values of exports. If
1233it is called before the module is linked, an <a href="errors.html#err_vm_module_status"><code>ERR_VM_MODULE_STATUS</code></a> error
1234will be thrown.</p>
1235
1236<pre class="with-30-chars"><input class="js-flavor-selector" 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>;
1237
1238<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> {
1239  m.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'x'</span>, <span class="hljs-number">1</span>);
1240});
1241
1242<span class="hljs-keyword">await</span> m.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> {});
1243<span class="hljs-keyword">await</span> m.evaluate();
1244
1245assert.<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>);
1246(<span class="hljs-keyword">async</span> () => {
1247  <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> {
1248    m.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'x'</span>, <span class="hljs-number">1</span>);
1249  });
1250  <span class="hljs-keyword">await</span> m.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> {});
1251  <span class="hljs-keyword">await</span> m.evaluate();
1252  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>);
1253})();</code><button class="copy-button">copy</button></pre>
1254</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>
1255<div class="api_metadata">
1256<details class="changelog"><summary>History</summary>
1257<table>
1258<tbody><tr><th>Version</th><th>Changes</th></tr>
1259<tr><td>v18.15.0</td>
1260<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>
1261<tr><td>v17.0.0, v16.12.0</td>
1262<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
1263<tr><td>v15.9.0</td>
1264<td><p>Added <code>importModuleDynamically</code> option again.</p></td></tr>
1265<tr><td>v14.3.0</td>
1266<td><p>Removal of <code>importModuleDynamically</code> due to compatibility issues.</p></td></tr>
1267<tr><td>v14.1.0, v13.14.0</td>
1268<td><p>The <code>importModuleDynamically</code> option is now supported.</p></td></tr>
1269<tr><td>v10.10.0</td>
1270<td><p><span>Added in: v10.10.0</span></p></td></tr>
1271</tbody></table>
1272</details>
1273</div>
1274<ul>
1275<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>
1276<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
1277function.</li>
1278<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
1279<ul>
1280<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
1281by this script. <strong>Default:</strong> <code>''</code>.</li>
1282<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
1283in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
1284<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
1285is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
1286<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
1287<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
1288source. This must be produced by a prior call to <a href="#vmcompilefunctioncode-params-options"><code>vm.compileFunction()</code></a>
1289with the same <code>code</code> and <code>params</code>.</li>
1290<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.
1291<strong>Default:</strong> <code>false</code>.</li>
1292<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
1293function should be compiled in.</li>
1294<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
1295extensions (objects wrapping the current scope) to be applied while
1296compiling. <strong>Default:</strong> <code>[]</code>.</li>
1297<li><code>importModuleDynamically</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 module
1298when <code>import()</code> is called. If this option is not specified, calls to
1299<code>import()</code> will reject with <a href="errors.html#err_vm_dynamic_import_callback_missing"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code></a>.
1300This option is part of the experimental modules API, and should not be
1301considered stable.  If <code>--experimental-vm-modules</code> isn't
1302set, this callback will be ignored and calls to <code>import()</code> will reject with
1303<a href="errors.html#err_vm_dynamic_import_callback_missing_flag"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG</code></a>.
1304<ul>
1305<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>
1306<li><code>function</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
1307<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
1308<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
1309was provided.</li>
1310<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
1311recommended in order to take advantage of error tracking, and to avoid
1312issues with namespaces that contain <code>then</code> function exports.</li>
1313</ul>
1314</li>
1315</ul>
1316</li>
1317<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
1318</ul>
1319<p>Compiles the given code into the provided context (if no context is
1320supplied, the current context is used), and returns it wrapped inside a
1321function with the given <code>params</code>.</p>
1322</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>
1323<div class="api_metadata">
1324<details class="changelog"><summary>History</summary>
1325<table>
1326<tbody><tr><th>Version</th><th>Changes</th></tr>
1327<tr><td>v14.6.0</td>
1328<td><p>The <code>microtaskMode</code> option is supported now.</p></td></tr>
1329<tr><td>v10.0.0</td>
1330<td><p>The first argument can no longer be a function.</p></td></tr>
1331<tr><td>v10.0.0</td>
1332<td><p>The <code>codeGeneration</code> option is supported now.</p></td></tr>
1333<tr><td>v0.3.1</td>
1334<td><p><span>Added in: v0.3.1</span></p></td></tr>
1335</tbody></table>
1336</details>
1337</div>
1338<ul>
1339<li><code>contextObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
1340<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
1341<ul>
1342<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.
1343<strong>Default:</strong> <code>'VM Context i'</code>, where <code>i</code> is an ascending numerical index of
1344the created context.</li>
1345<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
1346context for display purposes. The origin should be formatted like a URL,
1347but with only the scheme, host, and port (if necessary), like the value of
1348the <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
1349string should omit the trailing slash, as that denotes a path.
1350<strong>Default:</strong> <code>''</code>.</li>
1351<li><code>codeGeneration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
1352<ul>
1353<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
1354constructors (<code>Function</code>, <code>GeneratorFunction</code>, etc) will throw an
1355<code>EvalError</code>. <strong>Default:</strong> <code>true</code>.</li>
1356<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
1357module will throw a <code>WebAssembly.CompileError</code>. <strong>Default:</strong> <code>true</code>.</li>
1358</ul>
1359</li>
1360<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
1361scheduled through <code>Promise</code>s and <code>async function</code>s) will be run immediately
1362after a script has run through <a href="#scriptrunincontextcontextifiedobject-options"><code>script.runInContext()</code></a>.
1363They are included in the <code>timeout</code> and <code>breakOnSigint</code> scopes in that case.</li>
1364</ul>
1365</li>
1366<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>
1367</ul>
1368<p>If given a <code>contextObject</code>, the <code>vm.createContext()</code> method will <a href="#what-does-it-mean-to-contextify-an-object">prepare
1369that object</a> so that it can be used in calls to
1370<a href="#vmrunincontextcode-contextifiedobject-options"><code>vm.runInContext()</code></a> or <a href="#scriptrunincontextcontextifiedobject-options"><code>script.runInContext()</code></a>. Inside such scripts,
1371the <code>contextObject</code> will be the global object, retaining all of its existing
1372properties but also having the built-in objects and functions any standard
1373<a href="https://es5.github.io/#x15.1">global object</a> has. Outside of scripts run by the vm module, global variables
1374will remain unchanged.</p>
1375<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>);
1376
1377<span class="hljs-variable language_">global</span>.<span class="hljs-property">globalVar</span> = <span class="hljs-number">3</span>;
1378
1379<span class="hljs-keyword">const</span> context = { <span class="hljs-attr">globalVar</span>: <span class="hljs-number">1</span> };
1380vm.<span class="hljs-title function_">createContext</span>(context);
1381
1382vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalVar *= 2;'</span>, context);
1383
1384<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context);
1385<span class="hljs-comment">// Prints: { globalVar: 2 }</span>
1386
1387<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>);
1388<span class="hljs-comment">// Prints: 3</span></code> <button class="copy-button">copy</button></pre>
1389<p>If <code>contextObject</code> is omitted (or passed explicitly as <code>undefined</code>), a new,
1390empty <a href="#what-does-it-mean-to-contextify-an-object">contextified</a> object will be returned.</p>
1391<p>The <code>vm.createContext()</code> method is primarily useful for creating a single
1392context that can be used to run multiple scripts. For instance, if emulating a
1393web browser, the method can be used to create a single context representing a
1394window's global object, then run all <code>&#x3C;script></code> tags together within that
1395context.</p>
1396<p>The provided <code>name</code> and <code>origin</code> of the context are made visible through the
1397Inspector API.</p>
1398</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>
1399<div class="api_metadata">
1400<span>Added in: v0.11.7</span>
1401</div>
1402<ul>
1403<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>
1404<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
1405</ul>
1406<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
1407<a href="#vmcreatecontextcontextobject-options"><code>vm.createContext()</code></a>.</p>
1408</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>
1409<div class="api_metadata">
1410<span>Added in: v13.10.0</span>
1411</div>
1412<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
1413<p>Measure the memory known to V8 and used by all contexts known to the
1414current V8 isolate, or the main context.</p>
1415<ul>
1416<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.
1417<ul>
1418<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,
1419only the memory measured for the main context will be returned. In
1420detailed mode, the memory measured for all contexts known to the
1421current V8 isolate will be returned.
1422<strong>Default:</strong> <code>'summary'</code></li>
1423<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
1424execution, the promise will not resolve until after the next scheduled
1425garbage collection starts, which may take a while (or never if the program
1426exits before the next GC). With eager execution, the GC will be started
1427right away to measure the memory.
1428<strong>Default:</strong> <code>'default'</code></li>
1429</ul>
1430</li>
1431<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
1432resolve with an object containing information about the memory usage.
1433Otherwise it will be rejected with an <code>ERR_CONTEXT_NOT_INITIALIZED</code> error.</li>
1434</ul>
1435<p>The format of the object that the returned Promise may resolve with is
1436specific to the V8 engine and may change from one version of V8 to the next.</p>
1437<p>The returned result is different from the statistics returned by
1438<code>v8.getHeapSpaceStatistics()</code> in that <code>vm.measureMemory()</code> measure the
1439memory reachable by each V8 specific contexts in the current instance of
1440the V8 engine, while the result of <code>v8.getHeapSpaceStatistics()</code> measure
1441the memory occupied by each heap space in the current V8 instance.</p>
1442<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>);
1443<span class="hljs-comment">// Measure the memory used by the main context.</span>
1444vm.<span class="hljs-title function_">measureMemory</span>({ <span class="hljs-attr">mode</span>: <span class="hljs-string">'summary'</span> })
1445  <span class="hljs-comment">// This is the same as vm.measureMemory()</span>
1446  .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
1447    <span class="hljs-comment">// The current format is:</span>
1448    <span class="hljs-comment">// {</span>
1449    <span class="hljs-comment">//   total: {</span>
1450    <span class="hljs-comment">//      jsMemoryEstimate: 2418479, jsMemoryRange: [ 2418479, 2745799 ]</span>
1451    <span class="hljs-comment">//    }</span>
1452    <span class="hljs-comment">// }</span>
1453    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);
1454  });
1455
1456<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> });
1457vm.<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> })
1458  .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
1459    <span class="hljs-comment">// Reference the context here so that it won't be GC'ed</span>
1460    <span class="hljs-comment">// until the measurement is complete.</span>
1461    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">a</span>);
1462    <span class="hljs-comment">// {</span>
1463    <span class="hljs-comment">//   total: {</span>
1464    <span class="hljs-comment">//     jsMemoryEstimate: 2574732,</span>
1465    <span class="hljs-comment">//     jsMemoryRange: [ 2574732, 2904372 ]</span>
1466    <span class="hljs-comment">//   },</span>
1467    <span class="hljs-comment">//   current: {</span>
1468    <span class="hljs-comment">//     jsMemoryEstimate: 2438996,</span>
1469    <span class="hljs-comment">//     jsMemoryRange: [ 2438996, 2768636 ]</span>
1470    <span class="hljs-comment">//   },</span>
1471    <span class="hljs-comment">//   other: [</span>
1472    <span class="hljs-comment">//     {</span>
1473    <span class="hljs-comment">//       jsMemoryEstimate: 135736,</span>
1474    <span class="hljs-comment">//       jsMemoryRange: [ 135736, 465376 ]</span>
1475    <span class="hljs-comment">//     }</span>
1476    <span class="hljs-comment">//   ]</span>
1477    <span class="hljs-comment">// }</span>
1478    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);
1479  });</code> <button class="copy-button">copy</button></pre>
1480</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>
1481<div class="api_metadata">
1482<details class="changelog"><summary>History</summary>
1483<table>
1484<tbody><tr><th>Version</th><th>Changes</th></tr>
1485<tr><td>v17.0.0, v16.12.0</td>
1486<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
1487<tr><td>v6.3.0</td>
1488<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
1489<tr><td>v0.3.1</td>
1490<td><p><span>Added in: v0.3.1</span></p></td></tr>
1491</tbody></table>
1492</details>
1493</div>
1494<ul>
1495<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>
1496<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
1497as the <code>global</code> when the <code>code</code> is compiled and run.</li>
1498<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>
1499<ul>
1500<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
1501by this script. <strong>Default:</strong> <code>'evalmachine.&#x3C;anonymous>'</code>.</li>
1502<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
1503in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
1504<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
1505is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
1506<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
1507while compiling the <code>code</code>, the line of code causing the error is attached
1508to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
1509<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>
1510before terminating execution. If execution is terminated, an <a href="errors.html#class-error"><code>Error</code></a>
1511will be thrown. This value must be a strictly positive integer.</li>
1512<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>
1513(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
1514<a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
1515<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
1516work after that. <strong>Default:</strong> <code>false</code>.</li>
1517<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
1518<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
1519source.</li>
1520<li><code>importModuleDynamically</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 module
1521when <code>import()</code> is called. If this option is not specified, calls to
1522<code>import()</code> will reject with <a href="errors.html#err_vm_dynamic_import_callback_missing"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code></a>.
1523This option is part of the experimental modules API. We do not recommend
1524using it in a production environment.  If <code>--experimental-vm-modules</code> isn't
1525set, this callback will be ignored and calls to <code>import()</code> will reject with
1526<a href="errors.html#err_vm_dynamic_import_callback_missing_flag"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG</code></a>.
1527<ul>
1528<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>
1529<li><code>script</code> <a href="vm.html#class-vmscript" class="type">&#x3C;vm.Script></a></li>
1530<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
1531<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
1532was provided.</li>
1533<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
1534recommended in order to take advantage of error tracking, and to avoid
1535issues with namespaces that contain <code>then</code> function exports.</li>
1536</ul>
1537</li>
1538</ul>
1539</li>
1540<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>
1541</ul>
1542<p>The <code>vm.runInContext()</code> method compiles <code>code</code>, runs it within the context of
1543the <code>contextifiedObject</code>, then returns the result. Running code does not have
1544access to the local scope. The <code>contextifiedObject</code> object <em>must</em> have been
1545previously <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>
1546<p>If <code>options</code> is a string, then it specifies the filename.</p>
1547<p>The following example compiles and executes different scripts using a single
1548<a href="#what-does-it-mean-to-contextify-an-object">contextified</a> object:</p>
1549<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>);
1550
1551<span class="hljs-keyword">const</span> contextObject = { <span class="hljs-attr">globalVar</span>: <span class="hljs-number">1</span> };
1552vm.<span class="hljs-title function_">createContext</span>(contextObject);
1553
1554<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) {
1555  vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalVar *= 2;'</span>, contextObject);
1556}
1557<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contextObject);
1558<span class="hljs-comment">// Prints: { globalVar: 1024 }</span></code> <button class="copy-button">copy</button></pre>
1559</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>
1560<div class="api_metadata">
1561<details class="changelog"><summary>History</summary>
1562<table>
1563<tbody><tr><th>Version</th><th>Changes</th></tr>
1564<tr><td>v17.0.0, v16.12.0</td>
1565<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
1566<tr><td>v14.6.0</td>
1567<td><p>The <code>microtaskMode</code> option is supported now.</p></td></tr>
1568<tr><td>v10.0.0</td>
1569<td><p>The <code>contextCodeGeneration</code> option is supported now.</p></td></tr>
1570<tr><td>v6.3.0</td>
1571<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
1572<tr><td>v0.3.1</td>
1573<td><p><span>Added in: v0.3.1</span></p></td></tr>
1574</tbody></table>
1575</details>
1576</div>
1577<ul>
1578<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>
1579<li><code>contextObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> An object that will be <a href="#what-does-it-mean-to-contextify-an-object">contextified</a>. If
1580<code>undefined</code>, a new object will be created.</li>
1581<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>
1582<ul>
1583<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
1584by this script. <strong>Default:</strong> <code>'evalmachine.&#x3C;anonymous>'</code>.</li>
1585<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
1586in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
1587<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
1588is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
1589<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
1590while compiling the <code>code</code>, the line of code causing the error is attached
1591to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
1592<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>
1593before terminating execution. If execution is terminated, an <a href="errors.html#class-error"><code>Error</code></a>
1594will be thrown. This value must be a strictly positive integer.</li>
1595<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>
1596(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
1597<a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
1598<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
1599work after that. <strong>Default:</strong> <code>false</code>.</li>
1600<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.
1601<strong>Default:</strong> <code>'VM Context i'</code>, where <code>i</code> is an ascending numerical index of
1602the created context.</li>
1603<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
1604created context for display purposes. The origin should be formatted like a
1605URL, but with only the scheme, host, and port (if necessary), like the
1606value 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,
1607this string should omit the trailing slash, as that denotes a path.
1608<strong>Default:</strong> <code>''</code>.</li>
1609<li><code>contextCodeGeneration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
1610<ul>
1611<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
1612constructors (<code>Function</code>, <code>GeneratorFunction</code>, etc) will throw an
1613<code>EvalError</code>. <strong>Default:</strong> <code>true</code>.</li>
1614<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
1615module will throw a <code>WebAssembly.CompileError</code>. <strong>Default:</strong> <code>true</code>.</li>
1616</ul>
1617</li>
1618<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
1619<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
1620source.</li>
1621<li><code>importModuleDynamically</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 module
1622when <code>import()</code> is called. If this option is not specified, calls to
1623<code>import()</code> will reject with <a href="errors.html#err_vm_dynamic_import_callback_missing"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code></a>.
1624This option is part of the experimental modules API. We do not recommend
1625using it in a production environment. If <code>--experimental-vm-modules</code> isn't
1626set, this callback will be ignored and calls to <code>import()</code> will reject with
1627<a href="errors.html#err_vm_dynamic_import_callback_missing_flag"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG</code></a>.
1628<ul>
1629<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>
1630<li><code>script</code> <a href="vm.html#class-vmscript" class="type">&#x3C;vm.Script></a></li>
1631<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
1632<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
1633was provided.</li>
1634<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
1635recommended in order to take advantage of error tracking, and to avoid
1636issues with namespaces that contain <code>then</code> function exports.</li>
1637</ul>
1638</li>
1639<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
1640scheduled through <code>Promise</code>s and <code>async function</code>s) will be run immediately
1641after the script has run. They are included in the <code>timeout</code> and
1642<code>breakOnSigint</code> scopes in that case.</li>
1643</ul>
1644</li>
1645<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>
1646</ul>
1647<p>The <code>vm.runInNewContext()</code> first contextifies the given <code>contextObject</code> (or
1648creates a new <code>contextObject</code> if passed as <code>undefined</code>), compiles the <code>code</code>,
1649runs it within the created context, then returns the result. Running code
1650does not have access to the local scope.</p>
1651<p>If <code>options</code> is a string, then it specifies the filename.</p>
1652<p>The following example compiles and executes code that increments a global
1653variable and sets a new one. These globals are contained in the <code>contextObject</code>.</p>
1654<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>);
1655
1656<span class="hljs-keyword">const</span> contextObject = {
1657  <span class="hljs-attr">animal</span>: <span class="hljs-string">'cat'</span>,
1658  <span class="hljs-attr">count</span>: <span class="hljs-number">2</span>,
1659};
1660
1661vm.<span class="hljs-title function_">runInNewContext</span>(<span class="hljs-string">'count += 1; name = "kitty"'</span>, contextObject);
1662<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contextObject);
1663<span class="hljs-comment">// Prints: { animal: 'cat', count: 3, name: 'kitty' }</span></code> <button class="copy-button">copy</button></pre>
1664</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>
1665<div class="api_metadata">
1666<details class="changelog"><summary>History</summary>
1667<table>
1668<tbody><tr><th>Version</th><th>Changes</th></tr>
1669<tr><td>v17.0.0, v16.12.0</td>
1670<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
1671<tr><td>v6.3.0</td>
1672<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
1673<tr><td>v0.3.1</td>
1674<td><p><span>Added in: v0.3.1</span></p></td></tr>
1675</tbody></table>
1676</details>
1677</div>
1678<ul>
1679<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>
1680<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>
1681<ul>
1682<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
1683by this script. <strong>Default:</strong> <code>'evalmachine.&#x3C;anonymous>'</code>.</li>
1684<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
1685in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
1686<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
1687is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
1688<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
1689while compiling the <code>code</code>, the line of code causing the error is attached
1690to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
1691<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>
1692before terminating execution. If execution is terminated, an <a href="errors.html#class-error"><code>Error</code></a>
1693will be thrown. This value must be a strictly positive integer.</li>
1694<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>
1695(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
1696<a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
1697<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
1698work after that. <strong>Default:</strong> <code>false</code>.</li>
1699<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
1700<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
1701source.</li>
1702<li><code>importModuleDynamically</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 module
1703when <code>import()</code> is called. If this option is not specified, calls to
1704<code>import()</code> will reject with <a href="errors.html#err_vm_dynamic_import_callback_missing"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code></a>.
1705This option is part of the experimental modules API. We do not recommend
1706using it in a production environment. If <code>--experimental-vm-modules</code> isn't
1707set, this callback will be ignored and calls to <code>import()</code> will reject with
1708<a href="errors.html#err_vm_dynamic_import_callback_missing_flag"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG</code></a>.
1709<ul>
1710<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>
1711<li><code>script</code> <a href="vm.html#class-vmscript" class="type">&#x3C;vm.Script></a></li>
1712<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
1713<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
1714was provided.</li>
1715<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
1716recommended in order to take advantage of error tracking, and to avoid
1717issues with namespaces that contain <code>then</code> function exports.</li>
1718</ul>
1719</li>
1720</ul>
1721</li>
1722<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>
1723</ul>
1724<p><code>vm.runInThisContext()</code> compiles <code>code</code>, runs it within the context of the
1725current <code>global</code> and returns the result. Running code does not have access to
1726local scope, but does have access to the current <code>global</code> object.</p>
1727<p>If <code>options</code> is a string, then it specifies the filename.</p>
1728<p>The following example illustrates using both <code>vm.runInThisContext()</code> and
1729the 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>
1730<!-- eslint-disable prefer-const -->
1731<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>);
1732<span class="hljs-keyword">let</span> localVar = <span class="hljs-string">'initial value'</span>;
1733
1734<span class="hljs-keyword">const</span> vmResult = vm.<span class="hljs-title function_">runInThisContext</span>(<span class="hljs-string">'localVar = "vm";'</span>);
1735<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>);
1736<span class="hljs-comment">// Prints: vmResult: 'vm', localVar: 'initial value'</span>
1737
1738<span class="hljs-keyword">const</span> evalResult = <span class="hljs-built_in">eval</span>(<span class="hljs-string">'localVar = "eval";'</span>);
1739<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>);
1740<span class="hljs-comment">// Prints: evalResult: 'eval', localVar: 'eval'</span></code> <button class="copy-button">copy</button></pre>
1741<p>Because <code>vm.runInThisContext()</code> does not have access to the local scope,
1742<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
1743local scope, so the value <code>localVar</code> is changed. In this way
1744<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.
1745<code>(0,eval)('code')</code>.</p>
1746</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>
1747<p>When using either <a href="#scriptruninthiscontextoptions"><code>script.runInThisContext()</code></a> or
1748<a href="#vmruninthiscontextcode-options"><code>vm.runInThisContext()</code></a>, the code is executed within the current V8 global
1749context. The code passed to this VM context will have its own isolated scope.</p>
1750<p>In order to run a simple web server using the <code>node:http</code> module the code passed
1751to the context must either call <code>require('node:http')</code> on its own, or have a
1752reference to the <code>node:http</code> module passed to it. For instance:</p>
1753<pre><code class="language-js"><span class="hljs-meta">'use strict'</span>;
1754<span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
1755
1756<span class="hljs-keyword">const</span> code = <span class="hljs-string">`
1757((require) => {
1758  const http = require('node:http');
1759
1760  http.createServer((request, response) => {
1761    response.writeHead(200, { 'Content-Type': 'text/plain' });
1762    response.end('Hello World\\n');
1763  }).listen(8124);
1764
1765  console.log('Server running at http://127.0.0.1:8124/');
1766})`</span>;
1767
1768vm.<span class="hljs-title function_">runInThisContext</span>(code)(<span class="hljs-built_in">require</span>);</code> <button class="copy-button">copy</button></pre>
1769<p>The <code>require()</code> in the above case shares the state with the context it is
1770passed from. This may introduce risks when untrusted code is executed, e.g.
1771altering objects in the context in unwanted ways.</p>
1772</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>
1773<p>All JavaScript executed within Node.js runs within the scope of a "context".
1774According to the <a href="https://v8.dev/docs/embed#contexts">V8 Embedder's Guide</a>:</p>
1775<blockquote>
1776<p>In V8, a context is an execution environment that allows separate, unrelated,
1777JavaScript applications to run in a single instance of V8. You must explicitly
1778specify the context in which you want any JavaScript code to be run.</p>
1779</blockquote>
1780<p>When the method <code>vm.createContext()</code> is called, the <code>contextObject</code> argument
1781(or a newly-created object if <code>contextObject</code> is <code>undefined</code>) is associated
1782internally with a new instance of a V8 Context. This V8 Context provides the
1783<code>code</code> run using the <code>node:vm</code> module's methods with an isolated global
1784environment within which it can operate. The process of creating the V8 Context
1785and associating it with the <code>contextObject</code> is what this document refers to as
1786"contextifying" the object.</p>
1787</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>
1788<p><code>Promise</code>s and <code>async function</code>s can schedule tasks run by the JavaScript
1789engine asynchronously. By default, these tasks are run after all JavaScript
1790functions on the current stack are done executing.
1791This allows escaping the functionality of the <code>timeout</code> and
1792<code>breakOnSigint</code> options.</p>
1793<p>For example, the following code executed by <code>vm.runInNewContext()</code> with a
1794timeout of 5 milliseconds schedules an infinite loop to run after a promise
1795resolves. The scheduled loop is never interrupted by the timeout:</p>
1796<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>);
1797
1798<span class="hljs-keyword">function</span> <span class="hljs-title function_">loop</span>(<span class="hljs-params"></span>) {
1799  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'entering loop'</span>);
1800  <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>());
1801}
1802
1803vm.<span class="hljs-title function_">runInNewContext</span>(
1804  <span class="hljs-string">'Promise.resolve().then(() => loop());'</span>,
1805  { loop, <span class="hljs-variable language_">console</span> },
1806  { <span class="hljs-attr">timeout</span>: <span class="hljs-number">5</span> },
1807);
1808<span class="hljs-comment">// This is printed *before* 'entering loop' (!)</span>
1809<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>
1810<p>This can be addressed by passing <code>microtaskMode: 'afterEvaluate'</code> to the code
1811that creates the <code>Context</code>:</p>
1812<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>);
1813
1814<span class="hljs-keyword">function</span> <span class="hljs-title function_">loop</span>(<span class="hljs-params"></span>) {
1815  <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>());
1816}
1817
1818vm.<span class="hljs-title function_">runInNewContext</span>(
1819  <span class="hljs-string">'Promise.resolve().then(() => loop());'</span>,
1820  { loop, <span class="hljs-variable language_">console</span> },
1821  { <span class="hljs-attr">timeout</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">microtaskMode</span>: <span class="hljs-string">'afterEvaluate'</span> },
1822);</code> <button class="copy-button">copy</button></pre>
1823<p>In this case, the microtask scheduled through <code>promise.then()</code> will be run
1824before returning from <code>vm.runInNewContext()</code>, and will be interrupted
1825by the <code>timeout</code> functionality. This applies only to code running in a
1826<code>vm.Context</code>, so e.g. <a href="#vmruninthiscontextcode-options"><code>vm.runInThisContext()</code></a> does not take this option.</p>
1827<p>Promise callbacks are entered into the microtask queue of the context in which
1828they were created. For example, if <code>() => loop()</code> is replaced with just <code>loop</code>
1829in the above example, then <code>loop</code> will be pushed into the global microtask
1830queue, because it is a function from the outer (main) context, and thus will
1831also be able to escape the timeout.</p>
1832<p>If asynchronous scheduling functions such as <code>process.nextTick()</code>,
1833<code>queueMicrotask()</code>, <code>setTimeout()</code>, <code>setImmediate()</code>, etc. are made available
1834inside a <code>vm.Context</code>, functions passed to them will be added to global queues,
1835which are shared by all contexts. Therefore, callbacks passed to those functions
1836are not controllable through the timeout either.</p></section>
1837        <!-- API END -->
1838      </div>
1839    </div>
1840  </div>
1841</body>
1842</html>
1843