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