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