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