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