%PDF- %PDF-
Direktori : /usr/share/doc/nodejs/api/ |
Current File : //usr/share/doc/nodejs/api/vm.html |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <meta name="nodejs.org:node-version" content="v16.16.0"> <title>VM (executing JavaScript) | Node.js v16.16.0 Documentation</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback"> <link rel="stylesheet" href="assets/style.css"> <link rel="stylesheet" href="assets/hljs.css"> <link rel="canonical" href="https://nodejs.org/api/vm.html"> </head> <body class="alt apidoc" id="api-section-vm"> <div id="content" class="clearfix"> <div id="column2" class="interior"> <div id="intro" class="interior"> <a href="/" title="Go back to the home page"> Node.js </a> </div> <ul> <li><a href="documentation.html" class="nav-documentation">About this documentation</a></li> <li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li> </ul> <hr class="line"> <ul> <li><a href="assert.html" class="nav-assert">Assertion testing</a></li> <li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li> <li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li> <li><a href="buffer.html" class="nav-buffer">Buffer</a></li> <li><a href="addons.html" class="nav-addons">C++ addons</a></li> <li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li> <li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li> <li><a href="child_process.html" class="nav-child_process">Child processes</a></li> <li><a href="cluster.html" class="nav-cluster">Cluster</a></li> <li><a href="cli.html" class="nav-cli">Command-line options</a></li> <li><a href="console.html" class="nav-console">Console</a></li> <li><a href="corepack.html" class="nav-corepack">Corepack</a></li> <li><a href="crypto.html" class="nav-crypto">Crypto</a></li> <li><a href="debugger.html" class="nav-debugger">Debugger</a></li> <li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> <li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li> <li><a href="dns.html" class="nav-dns">DNS</a></li> <li><a href="domain.html" class="nav-domain">Domain</a></li> <li><a href="errors.html" class="nav-errors">Errors</a></li> <li><a href="events.html" class="nav-events">Events</a></li> <li><a href="fs.html" class="nav-fs">File system</a></li> <li><a href="globals.html" class="nav-globals">Globals</a></li> <li><a href="http.html" class="nav-http">HTTP</a></li> <li><a href="http2.html" class="nav-http2">HTTP/2</a></li> <li><a href="https.html" class="nav-https">HTTPS</a></li> <li><a href="inspector.html" class="nav-inspector">Inspector</a></li> <li><a href="intl.html" class="nav-intl">Internationalization</a></li> <li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li> <li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li> <li><a href="module.html" class="nav-module">Modules: <code>module</code> API</a></li> <li><a href="packages.html" class="nav-packages">Modules: Packages</a></li> <li><a href="net.html" class="nav-net">Net</a></li> <li><a href="os.html" class="nav-os">OS</a></li> <li><a href="path.html" class="nav-path">Path</a></li> <li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li> <li><a href="policy.html" class="nav-policy">Policies</a></li> <li><a href="process.html" class="nav-process">Process</a></li> <li><a href="punycode.html" class="nav-punycode">Punycode</a></li> <li><a href="querystring.html" class="nav-querystring">Query strings</a></li> <li><a href="readline.html" class="nav-readline">Readline</a></li> <li><a href="repl.html" class="nav-repl">REPL</a></li> <li><a href="report.html" class="nav-report">Report</a></li> <li><a href="stream.html" class="nav-stream">Stream</a></li> <li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li> <li><a href="timers.html" class="nav-timers">Timers</a></li> <li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> <li><a href="tracing.html" class="nav-tracing">Trace events</a></li> <li><a href="tty.html" class="nav-tty">TTY</a></li> <li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li> <li><a href="url.html" class="nav-url">URL</a></li> <li><a href="util.html" class="nav-util">Utilities</a></li> <li><a href="v8.html" class="nav-v8">V8</a></li> <li><a href="vm.html" class="nav-vm active">VM</a></li> <li><a href="wasi.html" class="nav-wasi">WASI</a></li> <li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li> <li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li> <li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li> <li><a href="zlib.html" class="nav-zlib">Zlib</a></li> </ul> <hr class="line"> <ul> <li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li> </ul> </div> <div id="column1" data-id="vm" class="interior"> <header class="header"> <div class="header-container"> <h1>Node.js v16.16.0 documentation</h1> <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden> <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24"> <path fill="none" d="M0 0h24v24H0z" /> <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"/> <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"/> </svg> <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24"> <path d="M0 0h24v24H0z" fill="none" /> <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"/> </svg> </button> </div> <div id="gtoc"> <ul> <li class="picker-header"> <a href="#"> <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> Table of contents </a> <div class="picker"><div class="toc"><ul> <li><span class="stability_2"><a href="#vm-executing-javascript">VM (executing JavaScript)</a></span> <ul> <li><a href="#class-vmscript">Class: <code>vm.Script</code></a> <ul> <li><a href="#new-vmscriptcode-options"><code>new vm.Script(code[, options])</code></a></li> <li><a href="#scriptcreatecacheddata"><code>script.createCachedData()</code></a></li> <li><a href="#scriptrunincontextcontextifiedobject-options"><code>script.runInContext(contextifiedObject[, options])</code></a></li> <li><a href="#scriptruninnewcontextcontextobject-options"><code>script.runInNewContext([contextObject[, options]])</code></a></li> <li><a href="#scriptruninthiscontextoptions"><code>script.runInThisContext([options])</code></a></li> </ul> </li> <li><span class="stability_1"><a href="#class-vmmodule">Class: <code>vm.Module</code></a></span> <ul> <li><a href="#moduledependencyspecifiers"><code>module.dependencySpecifiers</code></a></li> <li><a href="#moduleerror"><code>module.error</code></a></li> <li><a href="#moduleevaluateoptions"><code>module.evaluate([options])</code></a></li> <li><a href="#moduleidentifier"><code>module.identifier</code></a></li> <li><a href="#modulelinklinker"><code>module.link(linker)</code></a></li> <li><a href="#modulenamespace"><code>module.namespace</code></a></li> <li><a href="#modulestatus"><code>module.status</code></a></li> </ul> </li> <li><span class="stability_1"><a href="#class-vmsourcetextmodule">Class: <code>vm.SourceTextModule</code></a></span> <ul> <li><a href="#new-vmsourcetextmodulecode-options"><code>new vm.SourceTextModule(code[, options])</code></a></li> <li><a href="#sourcetextmodulecreatecacheddata"><code>sourceTextModule.createCachedData()</code></a></li> </ul> </li> <li><span class="stability_1"><a href="#class-vmsyntheticmodule">Class: <code>vm.SyntheticModule</code></a></span> <ul> <li><a href="#new-vmsyntheticmoduleexportnames-evaluatecallback-options"><code>new vm.SyntheticModule(exportNames, evaluateCallback[, options])</code></a></li> <li><a href="#syntheticmodulesetexportname-value"><code>syntheticModule.setExport(name, value)</code></a></li> </ul> </li> <li><a href="#vmcompilefunctioncode-params-options"><code>vm.compileFunction(code[, params[, options]])</code></a></li> <li><a href="#vmcreatecontextcontextobject-options"><code>vm.createContext([contextObject[, options]])</code></a></li> <li><a href="#vmiscontextobject"><code>vm.isContext(object)</code></a></li> <li><span class="stability_1"><a href="#vmmeasurememoryoptions"><code>vm.measureMemory([options])</code></a></span></li> <li><a href="#vmrunincontextcode-contextifiedobject-options"><code>vm.runInContext(code, contextifiedObject[, options])</code></a></li> <li><a href="#vmruninnewcontextcode-contextobject-options"><code>vm.runInNewContext(code[, contextObject[, options]])</code></a></li> <li><a href="#vmruninthiscontextcode-options"><code>vm.runInThisContext(code[, options])</code></a></li> <li><a href="#example-running-an-http-server-within-a-vm">Example: Running an HTTP server within a VM</a></li> <li><a href="#what-does-it-mean-to-contextify-an-object">What does it mean to "contextify" an object?</a></li> <li><a href="#timeout-interactions-with-asynchronous-tasks-and-promises">Timeout interactions with asynchronous tasks and Promises</a></li> </ul> </li> </ul></div></div> </li> <li class="picker-header"> <a href="#"> <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> Index </a> <div class="picker"><ul> <li><a href="documentation.html" class="nav-documentation">About this documentation</a></li> <li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li> <li> <a href="index.html">Index</a> </li> </ul> <hr class="line"> <ul> <li><a href="assert.html" class="nav-assert">Assertion testing</a></li> <li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li> <li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li> <li><a href="buffer.html" class="nav-buffer">Buffer</a></li> <li><a href="addons.html" class="nav-addons">C++ addons</a></li> <li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li> <li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li> <li><a href="child_process.html" class="nav-child_process">Child processes</a></li> <li><a href="cluster.html" class="nav-cluster">Cluster</a></li> <li><a href="cli.html" class="nav-cli">Command-line options</a></li> <li><a href="console.html" class="nav-console">Console</a></li> <li><a href="corepack.html" class="nav-corepack">Corepack</a></li> <li><a href="crypto.html" class="nav-crypto">Crypto</a></li> <li><a href="debugger.html" class="nav-debugger">Debugger</a></li> <li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> <li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li> <li><a href="dns.html" class="nav-dns">DNS</a></li> <li><a href="domain.html" class="nav-domain">Domain</a></li> <li><a href="errors.html" class="nav-errors">Errors</a></li> <li><a href="events.html" class="nav-events">Events</a></li> <li><a href="fs.html" class="nav-fs">File system</a></li> <li><a href="globals.html" class="nav-globals">Globals</a></li> <li><a href="http.html" class="nav-http">HTTP</a></li> <li><a href="http2.html" class="nav-http2">HTTP/2</a></li> <li><a href="https.html" class="nav-https">HTTPS</a></li> <li><a href="inspector.html" class="nav-inspector">Inspector</a></li> <li><a href="intl.html" class="nav-intl">Internationalization</a></li> <li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li> <li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li> <li><a href="module.html" class="nav-module">Modules: <code>module</code> API</a></li> <li><a href="packages.html" class="nav-packages">Modules: Packages</a></li> <li><a href="net.html" class="nav-net">Net</a></li> <li><a href="os.html" class="nav-os">OS</a></li> <li><a href="path.html" class="nav-path">Path</a></li> <li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li> <li><a href="policy.html" class="nav-policy">Policies</a></li> <li><a href="process.html" class="nav-process">Process</a></li> <li><a href="punycode.html" class="nav-punycode">Punycode</a></li> <li><a href="querystring.html" class="nav-querystring">Query strings</a></li> <li><a href="readline.html" class="nav-readline">Readline</a></li> <li><a href="repl.html" class="nav-repl">REPL</a></li> <li><a href="report.html" class="nav-report">Report</a></li> <li><a href="stream.html" class="nav-stream">Stream</a></li> <li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li> <li><a href="timers.html" class="nav-timers">Timers</a></li> <li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> <li><a href="tracing.html" class="nav-tracing">Trace events</a></li> <li><a href="tty.html" class="nav-tty">TTY</a></li> <li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li> <li><a href="url.html" class="nav-url">URL</a></li> <li><a href="util.html" class="nav-util">Utilities</a></li> <li><a href="v8.html" class="nav-v8">V8</a></li> <li><a href="vm.html" class="nav-vm active">VM</a></li> <li><a href="wasi.html" class="nav-wasi">WASI</a></li> <li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li> <li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li> <li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li> <li><a href="zlib.html" class="nav-zlib">Zlib</a></li> </ul> <hr class="line"> <ul> <li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li> </ul></div> </li> <li class="picker-header"> <a href="#"> <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> Other versions </a> <div class="picker"><ol id="alt-docs"><li><a href="https://nodejs.org/docs/latest-v18.x/api/vm.html">18.x</a></li> <li><a href="https://nodejs.org/docs/latest-v17.x/api/vm.html">17.x</a></li> <li><a href="https://nodejs.org/docs/latest-v16.x/api/vm.html">16.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v15.x/api/vm.html">15.x</a></li> <li><a href="https://nodejs.org/docs/latest-v14.x/api/vm.html">14.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v13.x/api/vm.html">13.x</a></li> <li><a href="https://nodejs.org/docs/latest-v12.x/api/vm.html">12.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v11.x/api/vm.html">11.x</a></li> <li><a href="https://nodejs.org/docs/latest-v10.x/api/vm.html">10.x</a></li> <li><a href="https://nodejs.org/docs/latest-v9.x/api/vm.html">9.x</a></li> <li><a href="https://nodejs.org/docs/latest-v8.x/api/vm.html">8.x</a></li> <li><a href="https://nodejs.org/docs/latest-v7.x/api/vm.html">7.x</a></li> <li><a href="https://nodejs.org/docs/latest-v6.x/api/vm.html">6.x</a></li> <li><a href="https://nodejs.org/docs/latest-v5.x/api/vm.html">5.x</a></li> <li><a href="https://nodejs.org/docs/latest-v4.x/api/vm.html">4.x</a></li> <li><a href="https://nodejs.org/docs/latest-v0.12.x/api/vm.html">0.12.x</a></li> <li><a href="https://nodejs.org/docs/latest-v0.10.x/api/vm.html">0.10.x</a></li></ol></div> </li> <li class="picker-header"> <a href="#"> <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> Options </a> <div class="picker"> <ul> <li> <a href="all.html">View on single page</a> </li> <li> <a href="vm.json">View as JSON</a> </li> <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/master/doc/api/vm.md">Edit on GitHub</a></li> </ul> </div> </li> </ul> </div> <hr> </header> <details id="toc" open><summary>Table of contents</summary><ul> <li><span class="stability_2"><a href="#vm-executing-javascript">VM (executing JavaScript)</a></span> <ul> <li><a href="#class-vmscript">Class: <code>vm.Script</code></a> <ul> <li><a href="#new-vmscriptcode-options"><code>new vm.Script(code[, options])</code></a></li> <li><a href="#scriptcreatecacheddata"><code>script.createCachedData()</code></a></li> <li><a href="#scriptrunincontextcontextifiedobject-options"><code>script.runInContext(contextifiedObject[, options])</code></a></li> <li><a href="#scriptruninnewcontextcontextobject-options"><code>script.runInNewContext([contextObject[, options]])</code></a></li> <li><a href="#scriptruninthiscontextoptions"><code>script.runInThisContext([options])</code></a></li> </ul> </li> <li><span class="stability_1"><a href="#class-vmmodule">Class: <code>vm.Module</code></a></span> <ul> <li><a href="#moduledependencyspecifiers"><code>module.dependencySpecifiers</code></a></li> <li><a href="#moduleerror"><code>module.error</code></a></li> <li><a href="#moduleevaluateoptions"><code>module.evaluate([options])</code></a></li> <li><a href="#moduleidentifier"><code>module.identifier</code></a></li> <li><a href="#modulelinklinker"><code>module.link(linker)</code></a></li> <li><a href="#modulenamespace"><code>module.namespace</code></a></li> <li><a href="#modulestatus"><code>module.status</code></a></li> </ul> </li> <li><span class="stability_1"><a href="#class-vmsourcetextmodule">Class: <code>vm.SourceTextModule</code></a></span> <ul> <li><a href="#new-vmsourcetextmodulecode-options"><code>new vm.SourceTextModule(code[, options])</code></a></li> <li><a href="#sourcetextmodulecreatecacheddata"><code>sourceTextModule.createCachedData()</code></a></li> </ul> </li> <li><span class="stability_1"><a href="#class-vmsyntheticmodule">Class: <code>vm.SyntheticModule</code></a></span> <ul> <li><a href="#new-vmsyntheticmoduleexportnames-evaluatecallback-options"><code>new vm.SyntheticModule(exportNames, evaluateCallback[, options])</code></a></li> <li><a href="#syntheticmodulesetexportname-value"><code>syntheticModule.setExport(name, value)</code></a></li> </ul> </li> <li><a href="#vmcompilefunctioncode-params-options"><code>vm.compileFunction(code[, params[, options]])</code></a></li> <li><a href="#vmcreatecontextcontextobject-options"><code>vm.createContext([contextObject[, options]])</code></a></li> <li><a href="#vmiscontextobject"><code>vm.isContext(object)</code></a></li> <li><span class="stability_1"><a href="#vmmeasurememoryoptions"><code>vm.measureMemory([options])</code></a></span></li> <li><a href="#vmrunincontextcode-contextifiedobject-options"><code>vm.runInContext(code, contextifiedObject[, options])</code></a></li> <li><a href="#vmruninnewcontextcode-contextobject-options"><code>vm.runInNewContext(code[, contextObject[, options]])</code></a></li> <li><a href="#vmruninthiscontextcode-options"><code>vm.runInThisContext(code[, options])</code></a></li> <li><a href="#example-running-an-http-server-within-a-vm">Example: Running an HTTP server within a VM</a></li> <li><a href="#what-does-it-mean-to-contextify-an-object">What does it mean to "contextify" an object?</a></li> <li><a href="#timeout-interactions-with-asynchronous-tasks-and-promises">Timeout interactions with asynchronous tasks and Promises</a></li> </ul> </li> </ul></details> <div id="apicontent"> <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> <p></p><div class="api_stability api_stability_2"><a href="documentation.html#stability-index">Stability: 2</a> - Stable</div><p></p> <p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v16.16.0/lib/vm.js">lib/vm.js</a></p> <p>The <code>vm</code> module enables compiling and running code within V8 Virtual Machine contexts.</p> <p><strong class="critical">The <code>vm</code> module is not a security mechanism. Do not use it to run untrusted code.</strong></p> <p>JavaScript code can be compiled and run immediately or compiled, saved, and run later.</p> <p>A common use case is to run the code in a different V8 Context. This means invoked code has a different global object than the invoking code.</p> <p>One can provide the context by <a href="#what-does-it-mean-to-contextify-an-object"><em>contextifying</em></a> an object. The invoked code treats any property in the context like a global variable. Any changes to global variables caused by the invoked code are reflected in the context object.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'vm'</span>); <span class="hljs-keyword">const</span> x = <span class="hljs-number">1</span>; <span class="hljs-keyword">const</span> context = { <span class="hljs-attr">x</span>: <span class="hljs-number">2</span> }; vm.<span class="hljs-title function_">createContext</span>(context); <span class="hljs-comment">// Contextify the object.</span> <span class="hljs-keyword">const</span> code = <span class="hljs-string">'x += 40; var y = 17;'</span>; <span class="hljs-comment">// `x` and `y` are global variables in the context.</span> <span class="hljs-comment">// Initially, x has the value 2 because that is the value of context.x.</span> vm.<span class="hljs-title function_">runInContext</span>(code, context); <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> <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> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(x); <span class="hljs-comment">// 1; y is not defined.</span></code></pre> <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> <div class="api_metadata"> <span>Added in: v0.3.1</span> </div> <p>Instances of the <code>vm.Script</code> class contain precompiled scripts that can be executed in specific contexts.</p> <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> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v16.12.0</td> <td><p>Added support for import assertions to the <code>importModuleDynamically</code> parameter.</p></td></tr> <tr><td>v10.6.0</td> <td><p>The <code>produceCachedData</code> is deprecated in favour of <code>script.createCachedData()</code>.</p></td></tr> <tr><td>v5.7.0</td> <td><p>The <code>cachedData</code> and <code>produceCachedData</code> options are supported now.</p></td></tr> <tr><td>v0.3.1</td> <td><p><span>Added in: v0.3.1</span></p></td></tr> </tbody></table> </details> </div> <ul> <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> <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> <ul> <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 by this script. <strong>Default:</strong> <code>'evalmachine.<anonymous>'</code>.</li> <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 in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li> <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 is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li> <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 <code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied source. When supplied, the <code>cachedDataRejected</code> value will be set to either <code>true</code> or <code>false</code> depending on acceptance of the data by V8.</li> <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 will attempt to produce code cache data for <code>code</code>. Upon success, a <code>Buffer</code> with V8's code cache data will be produced and stored in the <code>cachedData</code> property of the returned <code>vm.Script</code> instance. The <code>cachedDataProduced</code> value will be set to either <code>true</code> or <code>false</code> depending on whether code cache data is produced successfully. This option is <strong>deprecated</strong> in favor of <code>script.createCachedData()</code>. <strong>Default:</strong> <code>false</code>.</li> <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 when <code>import()</code> is called. If this option is not specified, calls to <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>. This option is part of the experimental modules API. We do not recommend using it in a production environment. <ul> <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> <li><code>script</code> <a href="vm.html#class-vmscript" class="type"><vm.Script></a></li> <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 <a href="https://tc39.es/proposal-import-assertions/#sec-evaluate-import-call"><code>optionsExpression</code></a> optional parameter, or an empty object if no value was provided.</li> <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 recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain <code>then</code> function exports.</li> </ul> </li> </ul> </li> </ul> <p>If <code>options</code> is a string, then it specifies the filename.</p> <p>Creating a new <code>vm.Script</code> object compiles <code>code</code> but does not run it. The compiled <code>vm.Script</code> can be run later multiple times. The <code>code</code> is not bound to any global object; rather, it is bound before each run, just for that run.</p> <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> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li>Returns: <a href="buffer.html#class-buffer" class="type"><Buffer></a></li> </ul> <p>Creates a code cache that can be used with the <code>Script</code> constructor's <code>cachedData</code> option. Returns a <code>Buffer</code>. This method may be called at any time and any number of times.</p> <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">` function add(a, b) { return a + b; } const x = add(1, 2); `</span>); <span class="hljs-keyword">const</span> cacheWithoutX = script.<span class="hljs-title function_">createCachedData</span>(); script.<span class="hljs-title function_">runInThisContext</span>(); <span class="hljs-keyword">const</span> cacheWithX = script.<span class="hljs-title function_">createCachedData</span>();</code></pre> <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> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.3.0</td> <td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr> <tr><td>v0.3.1</td> <td><p><span>Added in: v0.3.1</span></p></td></tr> </tbody></table> </details> </div> <ul> <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 <code>vm.createContext()</code> method.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <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 while compiling the <code>code</code>, the line of code causing the error is attached to the stack trace. <strong>Default:</strong> <code>true</code>.</li> <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> before terminating execution. If execution is terminated, an <a href="errors.html#class-error"><code>Error</code></a> will be thrown. This value must be a strictly positive integer.</li> <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> (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an <a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via <code>process.on('SIGINT')</code> are disabled during script execution, but continue to work after that. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <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> </ul> <p>Runs the compiled code contained by the <code>vm.Script</code> object within the given <code>contextifiedObject</code> and returns the result. Running code does not have access to local scope.</p> <p>The following example compiles code that increments a global variable, sets the value of another global variable, then execute the code multiple times. The globals are contained in the <code>context</code> object.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'vm'</span>); <span class="hljs-keyword">const</span> context = { <span class="hljs-attr">animal</span>: <span class="hljs-string">'cat'</span>, <span class="hljs-attr">count</span>: <span class="hljs-number">2</span> }; <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>); vm.<span class="hljs-title function_">createContext</span>(context); <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) { script.<span class="hljs-title function_">runInContext</span>(context); } <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context); <span class="hljs-comment">// Prints: { animal: 'cat', count: 12, name: 'kitty' }</span></code></pre> <p>Using the <code>timeout</code> or <code>breakOnSigint</code> options will result in new event loops and corresponding threads being started, which have a non-zero performance overhead.</p> <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> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v14.6.0</td> <td><p>The <code>microtaskMode</code> option is supported now.</p></td></tr> <tr><td>v10.0.0</td> <td><p>The <code>contextCodeGeneration</code> option is supported now.</p></td></tr> <tr><td>v6.3.0</td> <td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr> <tr><td>v0.3.1</td> <td><p><span>Added in: v0.3.1</span></p></td></tr> </tbody></table> </details> </div> <ul> <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 <code>undefined</code>, a new object will be created.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <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 while compiling the <code>code</code>, the line of code causing the error is attached to the stack trace. <strong>Default:</strong> <code>true</code>.</li> <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> before terminating execution. If execution is terminated, an <a href="errors.html#class-error"><code>Error</code></a> will be thrown. This value must be a strictly positive integer.</li> <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> (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an <a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via <code>process.on('SIGINT')</code> are disabled during script execution, but continue to work after that. <strong>Default:</strong> <code>false</code>.</li> <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. <strong>Default:</strong> <code>'VM Context i'</code>, where <code>i</code> is an ascending numerical index of the created context.</li> <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 created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value 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, this string should omit the trailing slash, as that denotes a path. <strong>Default:</strong> <code>''</code>.</li> <li><code>contextCodeGeneration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <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 constructors (<code>Function</code>, <code>GeneratorFunction</code>, etc) will throw an <code>EvalError</code>. <strong>Default:</strong> <code>true</code>.</li> <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 module will throw a <code>WebAssembly.CompileError</code>. <strong>Default:</strong> <code>true</code>.</li> </ul> </li> <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 scheduled through <code>Promise</code>s and <code>async function</code>s) will be run immediately after the script has run. They are included in the <code>timeout</code> and <code>breakOnSigint</code> scopes in that case.</li> </ul> </li> <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> </ul> <p>First contextifies the given <code>contextObject</code>, runs the compiled code contained by the <code>vm.Script</code> object within the created context, and returns the result. Running code does not have access to local scope.</p> <p>The following example compiles code that sets a global variable, then executes the code multiple times in different contexts. The globals are set on and contained within each individual <code>context</code>.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'vm'</span>); <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>); <span class="hljs-keyword">const</span> contexts = [{}, {}, {}]; contexts.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">context</span>) =></span> { script.<span class="hljs-title function_">runInNewContext</span>(context); }); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contexts); <span class="hljs-comment">// Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]</span></code></pre> <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> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.3.0</td> <td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr> <tr><td>v0.3.1</td> <td><p><span>Added in: v0.3.1</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <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 while compiling the <code>code</code>, the line of code causing the error is attached to the stack trace. <strong>Default:</strong> <code>true</code>.</li> <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> before terminating execution. If execution is terminated, an <a href="errors.html#class-error"><code>Error</code></a> will be thrown. This value must be a strictly positive integer.</li> <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> (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an <a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via <code>process.on('SIGINT')</code> are disabled during script execution, but continue to work after that. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <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> </ul> <p>Runs the compiled code contained by the <code>vm.Script</code> within the context of the current <code>global</code> object. Running code does not have access to local scope, but <em>does</em> have access to the current <code>global</code> object.</p> <p>The following example compiles code that increments a <code>global</code> variable then executes that code multiple times:</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'vm'</span>); <span class="hljs-variable language_">global</span>.<span class="hljs-property">globalVar</span> = <span class="hljs-number">0</span>; <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> }); <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) { script.<span class="hljs-title function_">runInThisContext</span>(); } <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(globalVar); <span class="hljs-comment">// 1000</span></code></pre> </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> <div class="api_metadata"> <span>Added in: v13.0.0, v12.16.0</span> </div> <p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> <p>This feature is only available with the <code>--experimental-vm-modules</code> command flag enabled.</p> <p>The <code>vm.Module</code> class provides a low-level interface for using ECMAScript modules in VM contexts. It is the counterpart of the <code>vm.Script</code> class 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 specification.</p> <p>Unlike <code>vm.Script</code> however, every <code>vm.Module</code> object is bound to a context from its creation. Operations on <code>vm.Module</code> objects are intrinsically asynchronous, in contrast with the synchronous nature of <code>vm.Script</code> objects. The use of 'async' functions can help with manipulating <code>vm.Module</code> objects.</p> <p>Using a <code>vm.Module</code> object requires three distinct steps: creation/parsing, linking, and evaluation. These three steps are illustrated in the following example.</p> <p>This implementation lies at a lower level than the <a href="esm.html#modules-ecmascript-modules">ECMAScript Module loader</a>. There is also no way to interact with the Loader yet, though support is planned.</p> <pre><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'vm'</span>; <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>, <span class="hljs-attr">print</span>: <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>, }); <span class="hljs-comment">// Step 1</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// Create a Module by constructing a new `vm.SourceTextModule` object. This</span> <span class="hljs-comment">// parses the provided source text, throwing a `SyntaxError` if anything goes</span> <span class="hljs-comment">// wrong. By default, a Module is created in the top context. But here, we</span> <span class="hljs-comment">// specify `contextifiedObject` as the context this Module belongs to.</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// Here, we attempt to obtain the default export from the module "foo", and</span> <span class="hljs-comment">// put it into local binding "secret".</span> <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">` import s from 'foo'; s; print(s); `</span>, { <span class="hljs-attr">context</span>: contextifiedObject }); <span class="hljs-comment">// Step 2</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// "Link" the imported dependencies of this Module to it.</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// The provided linking callback (the "linker") accepts two arguments: the</span> <span class="hljs-comment">// parent module (`bar` in this case) and the string that is the specifier of</span> <span class="hljs-comment">// the imported module. The callback is expected to return a Module that</span> <span class="hljs-comment">// corresponds to the provided specifier, with certain requirements documented</span> <span class="hljs-comment">// in `module.link()`.</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// If linking has not started for the returned Module, the same linker</span> <span class="hljs-comment">// callback will be called on the returned Module.</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// Even top-level Modules without dependencies must be explicitly linked. The</span> <span class="hljs-comment">// callback provided would never be called, however.</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// The link() method returns a Promise that will be resolved when all the</span> <span class="hljs-comment">// Promises returned by the linker resolve.</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// Note: This is a contrived example in that the linker function creates a new</span> <span class="hljs-comment">// "foo" module every time it is called. In a full-fledged module system, a</span> <span class="hljs-comment">// cache would probably be used to avoid duplicated modules.</span> <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>) { <span class="hljs-keyword">if</span> (specifier === <span class="hljs-string">'foo'</span>) { <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">` // The "secret" variable refers to the global variable we added to // "contextifiedObject" when creating the context. export default secret; `</span>, { <span class="hljs-attr">context</span>: referencingModule.<span class="hljs-property">context</span> }); <span class="hljs-comment">// Using `contextifiedObject` instead of `referencingModule.context`</span> <span class="hljs-comment">// here would work as well.</span> } <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>); } <span class="hljs-keyword">await</span> bar.<span class="hljs-title function_">link</span>(linker); <span class="hljs-comment">// Step 3</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// Evaluate the Module. The evaluate() method returns a promise which will</span> <span class="hljs-comment">// resolve after the module has finished evaluating.</span> <span class="hljs-comment">// Prints 42.</span> <span class="hljs-keyword">await</span> bar.evaluate();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'vm'</span>); <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>, <span class="hljs-attr">print</span>: <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>, }); (<span class="hljs-keyword">async</span> () => { <span class="hljs-comment">// Step 1</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// Create a Module by constructing a new `vm.SourceTextModule` object. This</span> <span class="hljs-comment">// parses the provided source text, throwing a `SyntaxError` if anything goes</span> <span class="hljs-comment">// wrong. By default, a Module is created in the top context. But here, we</span> <span class="hljs-comment">// specify `contextifiedObject` as the context this Module belongs to.</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// Here, we attempt to obtain the default export from the module "foo", and</span> <span class="hljs-comment">// put it into local binding "secret".</span> <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">` import s from 'foo'; s; print(s); `</span>, { <span class="hljs-attr">context</span>: contextifiedObject }); <span class="hljs-comment">// Step 2</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// "Link" the imported dependencies of this Module to it.</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// The provided linking callback (the "linker") accepts two arguments: the</span> <span class="hljs-comment">// parent module (`bar` in this case) and the string that is the specifier of</span> <span class="hljs-comment">// the imported module. The callback is expected to return a Module that</span> <span class="hljs-comment">// corresponds to the provided specifier, with certain requirements documented</span> <span class="hljs-comment">// in `module.link()`.</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// If linking has not started for the returned Module, the same linker</span> <span class="hljs-comment">// callback will be called on the returned Module.</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// Even top-level Modules without dependencies must be explicitly linked. The</span> <span class="hljs-comment">// callback provided would never be called, however.</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// The link() method returns a Promise that will be resolved when all the</span> <span class="hljs-comment">// Promises returned by the linker resolve.</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// Note: This is a contrived example in that the linker function creates a new</span> <span class="hljs-comment">// "foo" module every time it is called. In a full-fledged module system, a</span> <span class="hljs-comment">// cache would probably be used to avoid duplicated modules.</span> <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>) { <span class="hljs-keyword">if</span> (specifier === <span class="hljs-string">'foo'</span>) { <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">` // The "secret" variable refers to the global variable we added to // "contextifiedObject" when creating the context. export default secret; `</span>, { <span class="hljs-attr">context</span>: referencingModule.<span class="hljs-property">context</span> }); <span class="hljs-comment">// Using `contextifiedObject` instead of `referencingModule.context`</span> <span class="hljs-comment">// here would work as well.</span> } <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>); } <span class="hljs-keyword">await</span> bar.<span class="hljs-title function_">link</span>(linker); <span class="hljs-comment">// Step 3</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// Evaluate the Module. The evaluate() method returns a promise which will</span> <span class="hljs-comment">// resolve after the module has finished evaluating.</span> <span class="hljs-comment">// Prints 42.</span> <span class="hljs-keyword">await</span> bar.evaluate(); })();</code></pre> <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> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>The specifiers of all dependencies of this module. The returned array is frozen to disallow any changes to it.</p> <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 the ECMAScript specification.</p> <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> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>If the <code>module.status</code> is <code>'errored'</code>, this property contains the exception thrown by the module during evaluation. If the status is anything else, accessing this property will result in a thrown exception.</p> <p>The value <code>undefined</code> cannot be used for cases where there is not a thrown exception due to possible ambiguity with <code>throw undefined;</code>.</p> <p>Corresponds to the <code>[[EvaluationError]]</code> field of <a href="https://tc39.es/ecma262/#sec-cyclic-module-records">Cyclic Module Record</a>s in the ECMAScript specification.</p> <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> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <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 before terminating execution. If execution is interrupted, an <a href="errors.html#class-error"><code>Error</code></a> will be thrown. This value must be a strictly positive integer.</li> <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> (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an <a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via <code>process.on('SIGINT')</code> are disabled during script execution, but continue to work after that. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <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> </ul> <p>Evaluate the module.</p> <p>This must be called after the module has been linked; otherwise it will reject. It could be called also when the module has already been evaluated, in which case it will either do nothing if the initial evaluation ended in success (<code>module.status</code> is <code>'evaluated'</code>) or it will re-throw the exception that the initial evaluation resulted in (<code>module.status</code> is <code>'errored'</code>).</p> <p>This method cannot be called while the module is being evaluated (<code>module.status</code> is <code>'evaluating'</code>).</p> <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 Record</a>s in the ECMAScript specification.</p> <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> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The identifier of the current module, as set in the constructor.</p> <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> <ul> <li><code>linker</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> <ul> <li> <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> <pre><code class="language-js mjs"><span class="hljs-keyword">import</span> foo <span class="hljs-keyword">from</span> <span class="hljs-string">'foo'</span>; <span class="hljs-comment">// ^^^^^ the module specifier</span></code></pre> </li> <li> <p><code>extra</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <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: <!-- eslint-skip --> <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> }; <span class="hljs-comment">// ^^^^^^^^^^^^^^^^^ the assertion</span></code></pre> Per ECMA-262, hosts are expected to ignore assertions that they do not support, as opposed to, for example, triggering an error if an unsupported assertion is present.</li> </ul> </li> <li> <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> </li> <li> <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> </li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Link module dependencies. This method must be called before evaluation, and can only be called once per module.</p> <p>The function is expected to return a <code>Module</code> object or a <code>Promise</code> that eventually resolves to a <code>Module</code> object. The returned <code>Module</code> must satisfy the following two invariants:</p> <ul> <li>It must belong to the same context as the parent <code>Module</code>.</li> <li>Its <code>status</code> must not be <code>'errored'</code>.</li> </ul> <p>If the returned <code>Module</code>'s <code>status</code> is <code>'unlinked'</code>, this method will be recursively called on the returned <code>Module</code> with the same provided <code>linker</code> function.</p> <p><code>link()</code> returns a <code>Promise</code> that will either get resolved when all linking instances resolve to a valid <code>Module</code>, or rejected if the linker function either throws an exception or returns an invalid <code>Module</code>.</p> <p>The linker function roughly corresponds to the implementation-defined <a href="https://tc39.es/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> abstract operation in the ECMAScript specification, with a few key differences:</p> <ul> <li>The linker function is allowed to be asynchronous while <a href="https://tc39.es/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> is synchronous.</li> </ul> <p>The actual <a href="https://tc39.es/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> implementation used during module linking is one that returns the modules linked during linking. Since at that point all modules would have been fully linked already, the <a href="https://tc39.es/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> implementation is fully synchronous per specification.</p> <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 Record</a>s in the ECMAScript specification.</p> <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> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The namespace object of the module. This is only available after linking (<code>module.link()</code>) has completed.</p> <p>Corresponds to the <a href="https://tc39.es/ecma262/#sec-getmodulenamespace">GetModuleNamespace</a> abstract operation in the ECMAScript specification.</p> <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> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The current status of the module. Will be one of:</p> <ul> <li> <p><code>'unlinked'</code>: <code>module.link()</code> has not yet been called.</p> </li> <li> <p><code>'linking'</code>: <code>module.link()</code> has been called, but not all Promises returned by the linker function have been resolved yet.</p> </li> <li> <p><code>'linked'</code>: The module has been linked successfully, and all of its dependencies are linked, but <code>module.evaluate()</code> has not yet been called.</p> </li> <li> <p><code>'evaluating'</code>: The module is being evaluated through a <code>module.evaluate()</code> on itself or a parent module.</p> </li> <li> <p><code>'evaluated'</code>: The module has been successfully evaluated.</p> </li> <li> <p><code>'errored'</code>: The module has been evaluated, but an exception was thrown.</p> </li> </ul> <p>Other than <code>'errored'</code>, this status string corresponds to the specification's <a href="https://tc39.es/ecma262/#sec-cyclic-module-records">Cyclic Module Record</a>'s <code>[[Status]]</code> field. <code>'errored'</code> corresponds to <code>'evaluated'</code> in the specification, but with <code>[[EvaluationError]]</code> set to a value that is not <code>undefined</code>.</p> </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> <div class="api_metadata"> <span>Added in: v9.6.0</span> </div> <p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> <p>This feature is only available with the <code>--experimental-vm-modules</code> command flag enabled.</p> <ul> <li>Extends: <a href="vm.html#class-vmmodule" class="type"><vm.Module></a></li> </ul> <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 defined in the ECMAScript specification.</p> <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> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v16.12.0</td> <td><p>Added support for import assertions to the <code>importModuleDynamically</code> parameter.</p></td></tr> </tbody></table> </details> </div> <ul> <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> <li><code>options</code> <ul> <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. <strong>Default:</strong> <code>'vm:module(i)'</code> where <code>i</code> is a context-specific ascending index.</li> <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 <code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied source. The <code>code</code> must be the same as the module from which this <code>cachedData</code> was created.</li> <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 <code>vm.createContext()</code> method, to compile and evaluate this <code>Module</code> in.</li> <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 in stack traces produced by this <code>Module</code>. <strong>Default:</strong> <code>0</code>.</li> <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 is displayed in stack traces produced by this <code>Module</code>. <strong>Default:</strong> <code>0</code>.</li> <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> to initialize the <code>import.meta</code>. <ul> <li><code>meta</code> <a href="esm.html#importmeta" class="type"><import.meta></a></li> <li><code>module</code> <a href="vm.html#class-vmsourcetextmodule" class="type"><vm.SourceTextModule></a></li> </ul> </li> <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 when <code>import()</code> is called. If this option is not specified, calls to <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>. <ul> <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> <li><code>module</code> <a href="vm.html#class-vmmodule" class="type"><vm.Module></a></li> <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 <a href="https://tc39.es/proposal-import-assertions/#sec-evaluate-import-call"><code>optionsExpression</code></a> optional parameter, or an empty object if no value was provided.</li> <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 recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain <code>then</code> function exports.</li> </ul> </li> </ul> </li> </ul> <p>Creates a new <code>SourceTextModule</code> instance.</p> <p>Properties assigned to the <code>import.meta</code> object that are objects may allow the module to access information outside the specified <code>context</code>. Use <code>vm.runInContext()</code> to create objects in a specific context.</p> <pre><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'vm'</span>; <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> }); <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">'Object.getPrototypeOf(import.meta.prop).secret = secret;'</span>, { <span class="hljs-title function_">initializeImportMeta</span>(<span class="hljs-params">meta</span>) { <span class="hljs-comment">// Note: this object is created in the top context. As such,</span> <span class="hljs-comment">// Object.getPrototypeOf(import.meta.prop) points to the</span> <span class="hljs-comment">// Object.prototype in the top context rather than that in</span> <span class="hljs-comment">// the contextified object.</span> meta.<span class="hljs-property">prop</span> = {}; } }); <span class="hljs-comment">// Since module has no dependencies, the linker function will never be called.</span> <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> {}); <span class="hljs-keyword">await</span> <span class="hljs-variable language_">module</span>.evaluate(); <span class="hljs-comment">// Now, Object.prototype.secret will be equal to 42.</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// To fix this problem, replace</span> <span class="hljs-comment">// meta.prop = {};</span> <span class="hljs-comment">// above with</span> <span class="hljs-comment">// meta.prop = vm.runInContext('{}', contextifiedObject);</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'vm'</span>); <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> }); (<span class="hljs-keyword">async</span> () => { <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">'Object.getPrototypeOf(import.meta.prop).secret = secret;'</span>, { <span class="hljs-title function_">initializeImportMeta</span>(<span class="hljs-params">meta</span>) { <span class="hljs-comment">// Note: this object is created in the top context. As such,</span> <span class="hljs-comment">// Object.getPrototypeOf(import.meta.prop) points to the</span> <span class="hljs-comment">// Object.prototype in the top context rather than that in</span> <span class="hljs-comment">// the contextified object.</span> meta.<span class="hljs-property">prop</span> = {}; } }); <span class="hljs-comment">// Since module has no dependencies, the linker function will never be called.</span> <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> {}); <span class="hljs-keyword">await</span> <span class="hljs-variable language_">module</span>.evaluate(); <span class="hljs-comment">// Now, Object.prototype.secret will be equal to 42.</span> <span class="hljs-comment">//</span> <span class="hljs-comment">// To fix this problem, replace</span> <span class="hljs-comment">// meta.prop = {};</span> <span class="hljs-comment">// above with</span> <span class="hljs-comment">// meta.prop = vm.runInContext('{}', contextifiedObject);</span> })();</code></pre> <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> <div class="api_metadata"> <span>Added in: v13.7.0, v12.17.0</span> </div> <ul> <li>Returns: <a href="buffer.html#class-buffer" class="type"><Buffer></a></li> </ul> <p>Creates a code cache that can be used with the <code>SourceTextModule</code> constructor's <code>cachedData</code> option. Returns a <code>Buffer</code>. This method may be called any number of times before the module has been evaluated.</p> <pre><code class="language-js"><span class="hljs-comment">// Create an initial module</span> <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>); <span class="hljs-comment">// Create cached data from this module</span> <span class="hljs-keyword">const</span> cachedData = <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">createCachedData</span>(); <span class="hljs-comment">// Create a new module using the cached data. The code must be the same.</span> <span class="hljs-keyword">const</span> module2 = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">'const a = 1;'</span>, { cachedData });</code></pre> </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> <div class="api_metadata"> <span>Added in: v13.0.0, v12.16.0</span> </div> <p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> <p>This feature is only available with the <code>--experimental-vm-modules</code> command flag enabled.</p> <ul> <li>Extends: <a href="vm.html#class-vmmodule" class="type"><vm.Module></a></li> </ul> <p>The <code>vm.SyntheticModule</code> class provides the <a href="https://heycam.github.io/webidl/#synthetic-module-records">Synthetic Module Record</a> as defined in the WebIDL specification. The purpose of synthetic modules is to provide a generic interface for exposing non-JavaScript sources to ECMAScript module graphs.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'vm'</span>); <span class="hljs-keyword">const</span> source = <span class="hljs-string">'{ "a": 1 }'</span>; <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>) { <span class="hljs-keyword">const</span> obj = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(source); <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'default'</span>, obj); }); <span class="hljs-comment">// Use `module` in linking...</span></code></pre> <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> <div class="api_metadata"> <span>Added in: v13.0.0, v12.16.0</span> </div> <ul> <li><code>exportNames</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> Array of names that will be exported from the module.</li> <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> <li><code>options</code> <ul> <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. <strong>Default:</strong> <code>'vm:module(i)'</code> where <code>i</code> is a context-specific ascending index.</li> <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 <code>vm.createContext()</code> method, to compile and evaluate this <code>Module</code> in.</li> </ul> </li> </ul> <p>Creates a new <code>SyntheticModule</code> instance.</p> <p>Objects assigned to the exports of this instance may allow importers of the module to access information outside the specified <code>context</code>. Use <code>vm.runInContext()</code> to create objects in a specific context.</p> <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> <div class="api_metadata"> <span>Added in: v13.0.0, v12.16.0</span> </div> <ul> <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> <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> </ul> <p>This method is used after the module is linked to set the values of exports. If it is called before the module is linked, an <a href="errors.html#err_vm_module_status"><code>ERR_VM_MODULE_STATUS</code></a> error will be thrown.</p> <pre><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'vm'</span>; <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> { m.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'x'</span>, <span class="hljs-number">1</span>); }); <span class="hljs-keyword">await</span> m.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> {}); <span class="hljs-keyword">await</span> m.evaluate(); 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>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'vm'</span>); (<span class="hljs-keyword">async</span> () => { <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> { m.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'x'</span>, <span class="hljs-number">1</span>); }); <span class="hljs-keyword">await</span> m.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> {}); <span class="hljs-keyword">await</span> m.evaluate(); 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>); })();</code></pre> </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> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v16.12.0</td> <td><p>Added support for import assertions to the <code>importModuleDynamically</code> parameter.</p></td></tr> <tr><td>v15.9.0</td> <td><p>Added <code>importModuleDynamically</code> option again.</p></td></tr> <tr><td>v14.3.0</td> <td><p>Removal of <code>importModuleDynamically</code> due to compatibility issues.</p></td></tr> <tr><td>v14.1.0, v13.14.0</td> <td><p>The <code>importModuleDynamically</code> option is now supported.</p></td></tr> <tr><td>v10.10.0</td> <td><p><span>Added in: v10.10.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <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> <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 function.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <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 by this script. <strong>Default:</strong> <code>''</code>.</li> <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 in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li> <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 is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li> <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 <code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied source.</li> <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. <strong>Default:</strong> <code>false</code>.</li> <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 function should be compiled in.</li> <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 extensions (objects wrapping the current scope) to be applied while compiling. <strong>Default:</strong> <code>[]</code>.</li> <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 when <code>import()</code> is called. If this option is not specified, calls to <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>. This option is part of the experimental modules API, and should not be considered stable. <ul> <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> <li><code>function</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <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 <a href="https://tc39.es/proposal-import-assertions/#sec-evaluate-import-call"><code>optionsExpression</code></a> optional parameter, or an empty object if no value was provided.</li> <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 recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain <code>then</code> function exports.</li> </ul> </li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Compiles the given code into the provided context (if no context is supplied, the current context is used), and returns it wrapped inside a function with the given <code>params</code>.</p> </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> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v14.6.0</td> <td><p>The <code>microtaskMode</code> option is supported now.</p></td></tr> <tr><td>v10.0.0</td> <td><p>The first argument can no longer be a function.</p></td></tr> <tr><td>v10.0.0</td> <td><p>The <code>codeGeneration</code> option is supported now.</p></td></tr> <tr><td>v0.3.1</td> <td><p><span>Added in: v0.3.1</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>contextObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <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. <strong>Default:</strong> <code>'VM Context i'</code>, where <code>i</code> is an ascending numerical index of the created context.</li> <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 context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value 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, this string should omit the trailing slash, as that denotes a path. <strong>Default:</strong> <code>''</code>.</li> <li><code>codeGeneration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <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 constructors (<code>Function</code>, <code>GeneratorFunction</code>, etc) will throw an <code>EvalError</code>. <strong>Default:</strong> <code>true</code>.</li> <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 module will throw a <code>WebAssembly.CompileError</code>. <strong>Default:</strong> <code>true</code>.</li> </ul> </li> <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 scheduled through <code>Promise</code>s and <code>async function</code>s) will be run immediately after a script has run through <a href="#scriptrunincontextcontextifiedobject-options"><code>script.runInContext()</code></a>. They are included in the <code>timeout</code> and <code>breakOnSigint</code> scopes in that case.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> contextified object.</li> </ul> <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 that object</a> so that it can be used in calls to <a href="#vmrunincontextcode-contextifiedobject-options"><code>vm.runInContext()</code></a> or <a href="#scriptrunincontextcontextifiedobject-options"><code>script.runInContext()</code></a>. Inside such scripts, the <code>contextObject</code> will be the global object, retaining all of its existing properties but also having the built-in objects and functions any standard <a href="https://es5.github.io/#x15.1">global object</a> has. Outside of scripts run by the vm module, global variables will remain unchanged.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'vm'</span>); <span class="hljs-variable language_">global</span>.<span class="hljs-property">globalVar</span> = <span class="hljs-number">3</span>; <span class="hljs-keyword">const</span> context = { <span class="hljs-attr">globalVar</span>: <span class="hljs-number">1</span> }; vm.<span class="hljs-title function_">createContext</span>(context); vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalVar *= 2;'</span>, context); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context); <span class="hljs-comment">// Prints: { globalVar: 2 }</span> <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>); <span class="hljs-comment">// Prints: 3</span></code></pre> <p>If <code>contextObject</code> is omitted (or passed explicitly as <code>undefined</code>), a new, empty <a href="#what-does-it-mean-to-contextify-an-object">contextified</a> object will be returned.</p> <p>The <code>vm.createContext()</code> method is primarily useful for creating a single context that can be used to run multiple scripts. For instance, if emulating a web browser, the method can be used to create a single context representing a window's global object, then run all <code><script></code> tags together within that context.</p> <p>The provided <code>name</code> and <code>origin</code> of the context are made visible through the Inspector API.</p> </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> <div class="api_metadata"> <span>Added in: v0.11.7</span> </div> <ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <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 <a href="#vmcreatecontextcontextobject-options"><code>vm.createContext()</code></a>.</p> </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> <div class="api_metadata"> <span>Added in: v13.10.0</span> </div> <p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> <p>Measure the memory known to V8 and used by all contexts known to the current V8 isolate, or the main context.</p> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Optional. <ul> <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, only the memory measured for the main context will be returned. In detailed mode, the memory measured for all contexts known to the current V8 isolate will be returned. <strong>Default:</strong> <code>'summary'</code></li> <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 execution, the promise will not resolve until after the next scheduled garbage collection starts, which may take a while (or never if the program exits before the next GC). With eager execution, the GC will be started right away to measure the memory. <strong>Default:</strong> <code>'default'</code></li> </ul> </li> <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 resolve with an object containing information about the memory usage.</li> </ul> <p>The format of the object that the returned Promise may resolve with is specific to the V8 engine and may change from one version of V8 to the next.</p> <p>The returned result is different from the statistics returned by <code>v8.getHeapSpaceStatistics()</code> in that <code>vm.measureMemory()</code> measure the memory reachable by each V8 specific contexts in the current instance of the V8 engine, while the result of <code>v8.getHeapSpaceStatistics()</code> measure the memory occupied by each heap space in the current V8 instance.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'vm'</span>); <span class="hljs-comment">// Measure the memory used by the main context.</span> vm.<span class="hljs-title function_">measureMemory</span>({ <span class="hljs-attr">mode</span>: <span class="hljs-string">'summary'</span> }) <span class="hljs-comment">// This is the same as vm.measureMemory()</span> .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> { <span class="hljs-comment">// The current format is:</span> <span class="hljs-comment">// {</span> <span class="hljs-comment">// total: {</span> <span class="hljs-comment">// jsMemoryEstimate: 2418479, jsMemoryRange: [ 2418479, 2745799 ]</span> <span class="hljs-comment">// }</span> <span class="hljs-comment">// }</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result); }); <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> }); vm.<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> }) .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> { <span class="hljs-comment">// Reference the context here so that it won't be GC'ed</span> <span class="hljs-comment">// until the measurement is complete.</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">a</span>); <span class="hljs-comment">// {</span> <span class="hljs-comment">// total: {</span> <span class="hljs-comment">// jsMemoryEstimate: 2574732,</span> <span class="hljs-comment">// jsMemoryRange: [ 2574732, 2904372 ]</span> <span class="hljs-comment">// },</span> <span class="hljs-comment">// current: {</span> <span class="hljs-comment">// jsMemoryEstimate: 2438996,</span> <span class="hljs-comment">// jsMemoryRange: [ 2438996, 2768636 ]</span> <span class="hljs-comment">// },</span> <span class="hljs-comment">// other: [</span> <span class="hljs-comment">// {</span> <span class="hljs-comment">// jsMemoryEstimate: 135736,</span> <span class="hljs-comment">// jsMemoryRange: [ 135736, 465376 ]</span> <span class="hljs-comment">// }</span> <span class="hljs-comment">// ]</span> <span class="hljs-comment">// }</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result); });</code></pre> </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> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v16.12.0</td> <td><p>Added support for import assertions to the <code>importModuleDynamically</code> parameter.</p></td></tr> <tr><td>v6.3.0</td> <td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr> <tr><td>v0.3.1</td> <td><p><span>Added in: v0.3.1</span></p></td></tr> </tbody></table> </details> </div> <ul> <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> <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 as the <code>global</code> when the <code>code</code> is compiled and run.</li> <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> <ul> <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 by this script. <strong>Default:</strong> <code>'evalmachine.<anonymous>'</code>.</li> <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 in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li> <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 is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li> <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 while compiling the <code>code</code>, the line of code causing the error is attached to the stack trace. <strong>Default:</strong> <code>true</code>.</li> <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> before terminating execution. If execution is terminated, an <a href="errors.html#class-error"><code>Error</code></a> will be thrown. This value must be a strictly positive integer.</li> <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> (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an <a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via <code>process.on('SIGINT')</code> are disabled during script execution, but continue to work after that. <strong>Default:</strong> <code>false</code>.</li> <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 <code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied source. When supplied, the <code>cachedDataRejected</code> value will be set to either <code>true</code> or <code>false</code> depending on acceptance of the data by V8.</li> <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 will attempt to produce code cache data for <code>code</code>. Upon success, a <code>Buffer</code> with V8's code cache data will be produced and stored in the <code>cachedData</code> property of the returned <code>vm.Script</code> instance. The <code>cachedDataProduced</code> value will be set to either <code>true</code> or <code>false</code> depending on whether code cache data is produced successfully. This option is <strong>deprecated</strong> in favor of <code>script.createCachedData()</code>. <strong>Default:</strong> <code>false</code>.</li> <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 when <code>import()</code> is called. If this option is not specified, calls to <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>. This option is part of the experimental modules API. We do not recommend using it in a production environment. <ul> <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> <li><code>script</code> <a href="vm.html#class-vmscript" class="type"><vm.Script></a></li> <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 <a href="https://tc39.es/proposal-import-assertions/#sec-evaluate-import-call"><code>optionsExpression</code></a> optional parameter, or an empty object if no value was provided.</li> <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 recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain <code>then</code> function exports.</li> </ul> </li> </ul> </li> <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> </ul> <p>The <code>vm.runInContext()</code> method compiles <code>code</code>, runs it within the context of the <code>contextifiedObject</code>, then returns the result. Running code does not have access to the local scope. The <code>contextifiedObject</code> object <em>must</em> have been previously <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> <p>If <code>options</code> is a string, then it specifies the filename.</p> <p>The following example compiles and executes different scripts using a single <a href="#what-does-it-mean-to-contextify-an-object">contextified</a> object:</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'vm'</span>); <span class="hljs-keyword">const</span> contextObject = { <span class="hljs-attr">globalVar</span>: <span class="hljs-number">1</span> }; vm.<span class="hljs-title function_">createContext</span>(contextObject); <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) { vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalVar *= 2;'</span>, contextObject); } <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contextObject); <span class="hljs-comment">// Prints: { globalVar: 1024 }</span></code></pre> </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> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v16.12.0</td> <td><p>Added support for import assertions to the <code>importModuleDynamically</code> parameter.</p></td></tr> <tr><td>v14.6.0</td> <td><p>The <code>microtaskMode</code> option is supported now.</p></td></tr> <tr><td>v10.0.0</td> <td><p>The <code>contextCodeGeneration</code> option is supported now.</p></td></tr> <tr><td>v6.3.0</td> <td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr> <tr><td>v0.3.1</td> <td><p><span>Added in: v0.3.1</span></p></td></tr> </tbody></table> </details> </div> <ul> <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> <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 <code>undefined</code>, a new object will be created.</li> <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> <ul> <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 by this script. <strong>Default:</strong> <code>'evalmachine.<anonymous>'</code>.</li> <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 in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li> <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 is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li> <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 while compiling the <code>code</code>, the line of code causing the error is attached to the stack trace. <strong>Default:</strong> <code>true</code>.</li> <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> before terminating execution. If execution is terminated, an <a href="errors.html#class-error"><code>Error</code></a> will be thrown. This value must be a strictly positive integer.</li> <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> (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an <a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via <code>process.on('SIGINT')</code> are disabled during script execution, but continue to work after that. <strong>Default:</strong> <code>false</code>.</li> <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. <strong>Default:</strong> <code>'VM Context i'</code>, where <code>i</code> is an ascending numerical index of the created context.</li> <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 created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value 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, this string should omit the trailing slash, as that denotes a path. <strong>Default:</strong> <code>''</code>.</li> <li><code>contextCodeGeneration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <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 constructors (<code>Function</code>, <code>GeneratorFunction</code>, etc) will throw an <code>EvalError</code>. <strong>Default:</strong> <code>true</code>.</li> <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 module will throw a <code>WebAssembly.CompileError</code>. <strong>Default:</strong> <code>true</code>.</li> </ul> </li> <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 <code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied source. When supplied, the <code>cachedDataRejected</code> value will be set to either <code>true</code> or <code>false</code> depending on acceptance of the data by V8.</li> <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 will attempt to produce code cache data for <code>code</code>. Upon success, a <code>Buffer</code> with V8's code cache data will be produced and stored in the <code>cachedData</code> property of the returned <code>vm.Script</code> instance. The <code>cachedDataProduced</code> value will be set to either <code>true</code> or <code>false</code> depending on whether code cache data is produced successfully. This option is <strong>deprecated</strong> in favor of <code>script.createCachedData()</code>. <strong>Default:</strong> <code>false</code>.</li> <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 when <code>import()</code> is called. If this option is not specified, calls to <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>. This option is part of the experimental modules API. We do not recommend using it in a production environment. <ul> <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> <li><code>script</code> <a href="vm.html#class-vmscript" class="type"><vm.Script></a></li> <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 <a href="https://tc39.es/proposal-import-assertions/#sec-evaluate-import-call"><code>optionsExpression</code></a> optional parameter, or an empty object if no value was provided.</li> <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 recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain <code>then</code> function exports.</li> </ul> </li> <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 scheduled through <code>Promise</code>s and <code>async function</code>s) will be run immediately after the script has run. They are included in the <code>timeout</code> and <code>breakOnSigint</code> scopes in that case.</li> </ul> </li> <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> </ul> <p>The <code>vm.runInNewContext()</code> first contextifies the given <code>contextObject</code> (or creates a new <code>contextObject</code> if passed as <code>undefined</code>), compiles the <code>code</code>, runs it within the created context, then returns the result. Running code does not have access to the local scope.</p> <p>If <code>options</code> is a string, then it specifies the filename.</p> <p>The following example compiles and executes code that increments a global variable and sets a new one. These globals are contained in the <code>contextObject</code>.</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'vm'</span>); <span class="hljs-keyword">const</span> contextObject = { <span class="hljs-attr">animal</span>: <span class="hljs-string">'cat'</span>, <span class="hljs-attr">count</span>: <span class="hljs-number">2</span> }; vm.<span class="hljs-title function_">runInNewContext</span>(<span class="hljs-string">'count += 1; name = "kitty"'</span>, contextObject); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contextObject); <span class="hljs-comment">// Prints: { animal: 'cat', count: 3, name: 'kitty' }</span></code></pre> </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> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v16.12.0</td> <td><p>Added support for import assertions to the <code>importModuleDynamically</code> parameter.</p></td></tr> <tr><td>v6.3.0</td> <td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr> <tr><td>v0.3.1</td> <td><p><span>Added in: v0.3.1</span></p></td></tr> </tbody></table> </details> </div> <ul> <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> <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> <ul> <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 by this script. <strong>Default:</strong> <code>'evalmachine.<anonymous>'</code>.</li> <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 in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li> <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 is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li> <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 while compiling the <code>code</code>, the line of code causing the error is attached to the stack trace. <strong>Default:</strong> <code>true</code>.</li> <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> before terminating execution. If execution is terminated, an <a href="errors.html#class-error"><code>Error</code></a> will be thrown. This value must be a strictly positive integer.</li> <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> (<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an <a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via <code>process.on('SIGINT')</code> are disabled during script execution, but continue to work after that. <strong>Default:</strong> <code>false</code>.</li> <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 <code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied source. When supplied, the <code>cachedDataRejected</code> value will be set to either <code>true</code> or <code>false</code> depending on acceptance of the data by V8.</li> <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 will attempt to produce code cache data for <code>code</code>. Upon success, a <code>Buffer</code> with V8's code cache data will be produced and stored in the <code>cachedData</code> property of the returned <code>vm.Script</code> instance. The <code>cachedDataProduced</code> value will be set to either <code>true</code> or <code>false</code> depending on whether code cache data is produced successfully. This option is <strong>deprecated</strong> in favor of <code>script.createCachedData()</code>. <strong>Default:</strong> <code>false</code>.</li> <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 when <code>import()</code> is called. If this option is not specified, calls to <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>. This option is part of the experimental modules API. We do not recommend using it in a production environment. <ul> <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> <li><code>script</code> <a href="vm.html#class-vmscript" class="type"><vm.Script></a></li> <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 <a href="https://tc39.es/proposal-import-assertions/#sec-evaluate-import-call"><code>optionsExpression</code></a> optional parameter, or an empty object if no value was provided.</li> <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 recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain <code>then</code> function exports.</li> </ul> </li> </ul> </li> <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> </ul> <p><code>vm.runInThisContext()</code> compiles <code>code</code>, runs it within the context of the current <code>global</code> and returns the result. Running code does not have access to local scope, but does have access to the current <code>global</code> object.</p> <p>If <code>options</code> is a string, then it specifies the filename.</p> <p>The following example illustrates using both <code>vm.runInThisContext()</code> and the 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> <!-- eslint-disable prefer-const --> <pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'vm'</span>); <span class="hljs-keyword">let</span> localVar = <span class="hljs-string">'initial value'</span>; <span class="hljs-keyword">const</span> vmResult = vm.<span class="hljs-title function_">runInThisContext</span>(<span class="hljs-string">'localVar = "vm";'</span>); <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>); <span class="hljs-comment">// Prints: vmResult: 'vm', localVar: 'initial value'</span> <span class="hljs-keyword">const</span> evalResult = <span class="hljs-built_in">eval</span>(<span class="hljs-string">'localVar = "eval";'</span>); <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>); <span class="hljs-comment">// Prints: evalResult: 'eval', localVar: 'eval'</span></code></pre> <p>Because <code>vm.runInThisContext()</code> does not have access to the local scope, <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 local scope, so the value <code>localVar</code> is changed. In this way <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. <code>(0,eval)('code')</code>.</p> </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> <p>When using either <a href="#scriptruninthiscontextoptions"><code>script.runInThisContext()</code></a> or <a href="#vmruninthiscontextcode-options"><code>vm.runInThisContext()</code></a>, the code is executed within the current V8 global context. The code passed to this VM context will have its own isolated scope.</p> <p>In order to run a simple web server using the <code>http</code> module the code passed to the context must either call <code>require('http')</code> on its own, or have a reference to the <code>http</code> module passed to it. For instance:</p> <pre><code class="language-js"><span class="hljs-meta">'use strict'</span>; <span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'vm'</span>); <span class="hljs-keyword">const</span> code = <span class="hljs-string">` ((require) => { const http = require('http'); http.createServer((request, response) => { response.writeHead(200, { 'Content-Type': 'text/plain' }); response.end('Hello World\\n'); }).listen(8124); console.log('Server running at http://127.0.0.1:8124/'); })`</span>; vm.<span class="hljs-title function_">runInThisContext</span>(code)(<span class="hljs-built_in">require</span>);</code></pre> <p>The <code>require()</code> in the above case shares the state with the context it is passed from. This may introduce risks when untrusted code is executed, e.g. altering objects in the context in unwanted ways.</p> </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> <p>All JavaScript executed within Node.js runs within the scope of a "context". According to the <a href="https://v8.dev/docs/embed#contexts">V8 Embedder's Guide</a>:</p> <blockquote> <p>In V8, a context is an execution environment that allows separate, unrelated, JavaScript applications to run in a single instance of V8. You must explicitly specify the context in which you want any JavaScript code to be run.</p> </blockquote> <p>When the method <code>vm.createContext()</code> is called, the <code>contextObject</code> argument (or a newly-created object if <code>contextObject</code> is <code>undefined</code>) is associated internally with a new instance of a V8 Context. This V8 Context provides the <code>code</code> run using the <code>vm</code> module's methods with an isolated global environment within which it can operate. The process of creating the V8 Context and associating it with the <code>contextObject</code> is what this document refers to as "contextifying" the object.</p> </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> <p><code>Promise</code>s and <code>async function</code>s can schedule tasks run by the JavaScript engine asynchronously. By default, these tasks are run after all JavaScript functions on the current stack are done executing. This allows escaping the functionality of the <code>timeout</code> and <code>breakOnSigint</code> options.</p> <p>For example, the following code executed by <code>vm.runInNewContext()</code> with a timeout of 5 milliseconds schedules an infinite loop to run after a promise resolves. The scheduled loop is never interrupted by the timeout:</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'vm'</span>); <span class="hljs-keyword">function</span> <span class="hljs-title function_">loop</span>(<span class="hljs-params"></span>) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'entering loop'</span>); <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>()); } vm.<span class="hljs-title function_">runInNewContext</span>( <span class="hljs-string">'Promise.resolve().then(() => loop());'</span>, { loop, <span class="hljs-variable language_">console</span> }, { <span class="hljs-attr">timeout</span>: <span class="hljs-number">5</span> } ); <span class="hljs-comment">// This is printed *before* 'entering loop' (!)</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done executing'</span>);</code></pre> <p>This can be addressed by passing <code>microtaskMode: 'afterEvaluate'</code> to the code that creates the <code>Context</code>:</p> <pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'vm'</span>); <span class="hljs-keyword">function</span> <span class="hljs-title function_">loop</span>(<span class="hljs-params"></span>) { <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>()); } vm.<span class="hljs-title function_">runInNewContext</span>( <span class="hljs-string">'Promise.resolve().then(() => loop());'</span>, { loop, <span class="hljs-variable language_">console</span> }, { <span class="hljs-attr">timeout</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">microtaskMode</span>: <span class="hljs-string">'afterEvaluate'</span> } );</code></pre> <p>In this case, the microtask scheduled through <code>promise.then()</code> will be run before returning from <code>vm.runInNewContext()</code>, and will be interrupted by the <code>timeout</code> functionality. This applies only to code running in a <code>vm.Context</code>, so e.g. <a href="#vmruninthiscontextcode-options"><code>vm.runInThisContext()</code></a> does not take this option.</p> <p>Promise callbacks are entered into the microtask queue of the context in which they were created. For example, if <code>() => loop()</code> is replaced with just <code>loop</code> in the above example, then <code>loop</code> will be pushed into the global microtask queue, because it is a function from the outer (main) context, and thus will also be able to escape the timeout.</p> <p>If asynchronous scheduling functions such as <code>process.nextTick()</code>, <code>queueMicrotask()</code>, <code>setTimeout()</code>, <code>setImmediate()</code>, etc. are made available inside a <code>vm.Context</code>, functions passed to them will be added to global queues, which are shared by all contexts. Therefore, callbacks passed to those functions are not controllable through the timeout either.</p></section> <!-- API END --> </div> </div> </div> <script> 'use strict'; { const kCustomPreference = 'customDarkTheme'; const userSettings = sessionStorage.getItem(kCustomPreference); const themeToggleButton = document.getElementById('theme-toggle-btn'); if (userSettings === null && window.matchMedia) { const mq = window.matchMedia('(prefers-color-scheme: dark)'); if ('onchange' in mq) { function mqChangeListener(e) { document.documentElement.classList.toggle('dark-mode', e.matches); } mq.addEventListener('change', mqChangeListener); if (themeToggleButton) { themeToggleButton.addEventListener('click', function() { mq.removeEventListener('change', mqChangeListener); }, { once: true }); } } if (mq.matches) { document.documentElement.classList.add('dark-mode'); } } else if (userSettings === 'true') { document.documentElement.classList.add('dark-mode'); } if (themeToggleButton) { themeToggleButton.hidden = false; themeToggleButton.addEventListener('click', function() { sessionStorage.setItem( kCustomPreference, document.documentElement.classList.toggle('dark-mode') ); }); } } </script> </body> </html>