%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="v18.19.1"> <title>VM (executing JavaScript) | Node.js v18.19.1 Documentation</title> <link rel="stylesheet" href="assets/style.css"> <link rel="stylesheet" href="assets/hljs.css"> <script async defer src="assets/api.js" type="text/javascript"></script> __JS_FLAVORED_DYNAMIC_CSS__ </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="index.html" 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>node: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="permissions.html" class="nav-permissions">Permissions</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="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</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="test.html" class="nav-test">Test runner</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 v18.19.1 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="pinned-header">Node.js v18.19.1</li> <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><a href="#vm-executing-javascript">VM (executing JavaScript)</a><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="#scriptcacheddatarejected"><code>script.cachedDataRejected</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> <li><a href="#scriptsourcemapurl"><code>script.sourceMapURL</code></a></li> </ul> </li> <li><a href="#class-vmmodule">Class: <code>vm.Module</code></a><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><a href="#class-vmsourcetextmodule">Class: <code>vm.SourceTextModule</code></a><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><a href="#class-vmsyntheticmodule">Class: <code>vm.SyntheticModule</code></a><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><a href="#vmmeasurememoryoptions"><code>vm.measureMemory([options])</code></a></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>node: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="permissions.html" class="nav-permissions">Permissions</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="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</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="test.html" class="nav-test">Test runner</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 <b>LTS</b></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</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</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><a href="#vm-executing-javascript">VM (executing JavaScript)</a><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="#scriptcacheddatarejected"><code>script.cachedDataRejected</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> <li><a href="#scriptsourcemapurl"><code>script.sourceMapURL</code></a></li> </ul> </li> <li><a href="#class-vmmodule">Class: <code>vm.Module</code></a><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><a href="#class-vmsourcetextmodule">Class: <code>vm.SourceTextModule</code></a><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><a href="#class-vmsyntheticmodule">Class: <code>vm.SyntheticModule</code></a><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><a href="#vmmeasurememoryoptions"><code>vm.measureMemory([options])</code></a></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> <!--introduced_in=v0.10.0--> <blockquote> <p>Stability: 2 - Stable</p> </blockquote> <!--name=vm--> <!-- source_link=lib/vm.js --> <p>The <code>node:vm</code> module enables compiling and running code within V8 Virtual Machine contexts.</p> <p><strong class="critical">The <code>node: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">const vm = require('node:vm'); const x = 1; const context = { x: 2 }; vm.createContext(context); // Contextify the object. const code = 'x += 40; var y = 17;'; // `x` and `y` are global variables in the context. // Initially, x has the value 2 because that is the value of context.x. vm.runInContext(code, context); console.log(context.x); // 42 console.log(context.y); // 17 console.log(x); // 1; y is not defined. </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> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v17.0.0, v16.12.0</td> <td><p>Added support for import attributes 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> </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> {Object|string}<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> {Buffer|TypedArray|DataView} 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> {vm.Script}</li> <li><code>importAttributes</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-attributes/#sec-evaluate-import-call"><code>optionsExpression</code></a> optional parameter, or an empty object if no value was provided.</li> <li>Returns: {Module Namespace Object|vm.Module} 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.cachedDataRejected</code><span><a class="mark" href="#scriptcacheddatarejected" id="scriptcacheddatarejected">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_cacheddatarejected"></a></h4> <div class="api_metadata"> <span>Added in: v5.7.0</span> </div><ul> <li>{boolean|undefined}</li> </ul> <p>When <code>cachedData</code> is supplied to create the <code>vm.Script</code>, this value will be set to either <code>true</code> or <code>false</code> depending on acceptance of the data by V8. Otherwise the value is <code>undefined</code>.</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> <p>The code cache of the <code>Script</code> doesn't contain any JavaScript observable states. The code cache is safe to be saved along side the script source and used to construct new <code>Script</code> instances multiple times.</p> <p>Functions in the <code>Script</code> source can be marked as lazily compiled and they are not compiled at construction of the <code>Script</code>. These functions are going to be compiled when they are invoked the first time. The code cache serializes the metadata that V8 currently knows about the <code>Script</code> that it can use to speed up future compilations.</p> <pre><code class="language-js">const script = new vm.Script(` function add(a, b) { return a + b; } const x = add(1, 2); `); const cacheWithoutAdd = script.createCachedData(); // In `cacheWithoutAdd` the function `add()` is marked for full compilation // upon invocation. script.runInThisContext(); const cacheWithAdd = script.createCachedData(); // `cacheWithAdd` contains fully compiled function `add()`. </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> <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> </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">const vm = require('node:vm'); const context = { animal: 'cat', count: 2, }; const script = new vm.Script('count += 1; name = "kitty";'); vm.createContext(context); for (let i = 0; i < 10; ++i) { script.runInContext(context); } console.log(context); // Prints: { animal: 'cat', count: 12, name: 'kitty' } </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> <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> </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">const vm = require('node:vm'); const script = new vm.Script('globalVar = "set"'); const contexts = [{}, {}, {}]; contexts.forEach((context) => { script.runInNewContext(context); }); console.log(contexts); // Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] </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> <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> </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">const vm = require('node:vm'); global.globalVar = 0; const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); for (let i = 0; i < 1000; ++i) { script.runInThisContext(); } console.log(globalVar); // 1000 </code></pre> <h4><code>script.sourceMapURL</code><span><a class="mark" href="#scriptsourcemapurl" id="scriptsourcemapurl">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_sourcemapurl"></a></h4> <div class="api_metadata"> <span>Added in: v18.13.0</span> </div><ul> <li>{string|undefined}</li> </ul> <p>When the script is compiled from a source that contains a source map magic comment, this property will be set to the URL of the source map.</p> <pre><code class="language-mjs">import vm from 'node:vm'; const script = new vm.Script(` function myFunc() {} //# sourceMappingURL=sourcemap.json `); console.log(script.sourceMapURL); // Prints: sourcemap.json </code></pre> <pre><code class="language-cjs">const vm = require('node:vm'); const script = new vm.Script(` function myFunc() {} //# sourceMappingURL=sourcemap.json `); console.log(script.sourceMapURL); // Prints: sourcemap.json </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><blockquote> <p>Stability: 1 - Experimental</p> </blockquote> <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><code class="language-mjs">import vm from 'node:vm'; const contextifiedObject = vm.createContext({ secret: 42, print: console.log, }); // Step 1 // // Create a Module by constructing a new `vm.SourceTextModule` object. This // parses the provided source text, throwing a `SyntaxError` if anything goes // wrong. By default, a Module is created in the top context. But here, we // specify `contextifiedObject` as the context this Module belongs to. // // Here, we attempt to obtain the default export from the module "foo", and // put it into local binding "secret". const bar = new vm.SourceTextModule(` import s from 'foo'; s; print(s); `, { context: contextifiedObject }); // Step 2 // // "Link" the imported dependencies of this Module to it. // // The provided linking callback (the "linker") accepts two arguments: the // parent module (`bar` in this case) and the string that is the specifier of // the imported module. The callback is expected to return a Module that // corresponds to the provided specifier, with certain requirements documented // in `module.link()`. // // If linking has not started for the returned Module, the same linker // callback will be called on the returned Module. // // Even top-level Modules without dependencies must be explicitly linked. The // callback provided would never be called, however. // // The link() method returns a Promise that will be resolved when all the // Promises returned by the linker resolve. // // Note: This is a contrived example in that the linker function creates a new // "foo" module every time it is called. In a full-fledged module system, a // cache would probably be used to avoid duplicated modules. async function linker(specifier, referencingModule) { if (specifier === 'foo') { return new vm.SourceTextModule(` // The "secret" variable refers to the global variable we added to // "contextifiedObject" when creating the context. export default secret; `, { context: referencingModule.context }); // Using `contextifiedObject` instead of `referencingModule.context` // here would work as well. } throw new Error(`Unable to resolve dependency: ${specifier}`); } await bar.link(linker); // Step 3 // // Evaluate the Module. The evaluate() method returns a promise which will // resolve after the module has finished evaluating. // Prints 42. await bar.evaluate(); </code></pre> <pre><code class="language-cjs">const vm = require('node:vm'); const contextifiedObject = vm.createContext({ secret: 42, print: console.log, }); (async () => { // Step 1 // // Create a Module by constructing a new `vm.SourceTextModule` object. This // parses the provided source text, throwing a `SyntaxError` if anything goes // wrong. By default, a Module is created in the top context. But here, we // specify `contextifiedObject` as the context this Module belongs to. // // Here, we attempt to obtain the default export from the module "foo", and // put it into local binding "secret". const bar = new vm.SourceTextModule(` import s from 'foo'; s; print(s); `, { context: contextifiedObject }); // Step 2 // // "Link" the imported dependencies of this Module to it. // // The provided linking callback (the "linker") accepts two arguments: the // parent module (`bar` in this case) and the string that is the specifier of // the imported module. The callback is expected to return a Module that // corresponds to the provided specifier, with certain requirements documented // in `module.link()`. // // If linking has not started for the returned Module, the same linker // callback will be called on the returned Module. // // Even top-level Modules without dependencies must be explicitly linked. The // callback provided would never be called, however. // // The link() method returns a Promise that will be resolved when all the // Promises returned by the linker resolve. // // Note: This is a contrived example in that the linker function creates a new // "foo" module every time it is called. In a full-fledged module system, a // cache would probably be used to avoid duplicated modules. async function linker(specifier, referencingModule) { if (specifier === 'foo') { return new vm.SourceTextModule(` // The "secret" variable refers to the global variable we added to // "contextifiedObject" when creating the context. export default secret; `, { context: referencingModule.context }); // Using `contextifiedObject` instead of `referencingModule.context` // here would work as well. } throw new Error(`Unable to resolve dependency: ${specifier}`); } await bar.link(linker); // Step 3 // // Evaluate the Module. The evaluate() method returns a promise which will // resolve after the module has finished evaluating. // Prints 42. await 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> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v18.19.0</td> <td><p>The option <code>extra.assert</code> is renamed to <code>extra.attributes</code>. The former name is still provided for backward compatibility.</p> </td></tr> </table> </details> </div><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-mjs">import foo from 'foo'; // ^^^^^ the module specifier </code></pre> </li> <li><p><code>referencingModule</code> {vm.Module} The <code>Module</code> object <code>link()</code> is called on.</p> </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>attributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The data from the attribute:<pre><code class="language-mjs">import foo from 'foo' assert { name: 'value' }; // ^^^^^^^^^^^^^^^^^ the attribute </code></pre> Per ECMA-262, hosts are expected to trigger an error if an unsupported attribute is present.</li> <li><code>assert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Alias for <code>extra.attributes</code>.</li> </ul> </li> <li><p>Returns: {vm.Module|Promise}</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><blockquote> <p>Stability: 1 - Experimental</p> </blockquote> <p>This feature is only available with the <code>--experimental-vm-modules</code> command flag enabled.</p> <ul> <li>Extends: {vm.Module}</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> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v17.0.0, v16.12.0</td> <td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p> </td></tr> </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> {Buffer|TypedArray|DataView} 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. If no context is specified, the module is evaluated in the current execution context.</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> {import.meta}</li> <li><code>module</code> {vm.SourceTextModule}</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> {vm.Module}</li> <li><code>importAttributes</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-attributes/#sec-evaluate-import-call"><code>optionsExpression</code></a> optional parameter, or an empty object if no value was provided.</li> <li>Returns: {Module Namespace Object|vm.Module} 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><code class="language-mjs">import vm from 'node:vm'; const contextifiedObject = vm.createContext({ secret: 42 }); const module = new vm.SourceTextModule( 'Object.getPrototypeOf(import.meta.prop).secret = secret;', { initializeImportMeta(meta) { // Note: this object is created in the top context. As such, // Object.getPrototypeOf(import.meta.prop) points to the // Object.prototype in the top context rather than that in // the contextified object. meta.prop = {}; }, }); // Since module has no dependencies, the linker function will never be called. await module.link(() => {}); await module.evaluate(); // Now, Object.prototype.secret will be equal to 42. // // To fix this problem, replace // meta.prop = {}; // above with // meta.prop = vm.runInContext('{}', contextifiedObject); </code></pre> <pre><code class="language-cjs">const vm = require('node:vm'); const contextifiedObject = vm.createContext({ secret: 42 }); (async () => { const module = new vm.SourceTextModule( 'Object.getPrototypeOf(import.meta.prop).secret = secret;', { initializeImportMeta(meta) { // Note: this object is created in the top context. As such, // Object.getPrototypeOf(import.meta.prop) points to the // Object.prototype in the top context rather than that in // the contextified object. meta.prop = {}; }, }); // Since module has no dependencies, the linker function will never be called. await module.link(() => {}); await module.evaluate(); // Now, Object.prototype.secret will be equal to 42. // // To fix this problem, replace // meta.prop = {}; // above with // meta.prop = vm.runInContext('{}', contextifiedObject); })(); </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> <p>The code cache of the <code>SourceTextModule</code> doesn't contain any JavaScript observable states. The code cache is safe to be saved along side the script source and used to construct new <code>SourceTextModule</code> instances multiple times.</p> <p>Functions in the <code>SourceTextModule</code> source can be marked as lazily compiled and they are not compiled at construction of the <code>SourceTextModule</code>. These functions are going to be compiled when they are invoked the first time. The code cache serializes the metadata that V8 currently knows about the <code>SourceTextModule</code> that it can use to speed up future compilations.</p> <pre><code class="language-js">// Create an initial module const module = new vm.SourceTextModule('const a = 1;'); // Create cached data from this module const cachedData = module.createCachedData(); // Create a new module using the cached data. The code must be the same. const module2 = new vm.SourceTextModule('const a = 1;', { 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><blockquote> <p>Stability: 1 - Experimental</p> </blockquote> <p>This feature is only available with the <code>--experimental-vm-modules</code> command flag enabled.</p> <ul> <li>Extends: {vm.Module}</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">const vm = require('node:vm'); const source = '{ "a": 1 }'; const module = new vm.SyntheticModule(['default'], function() { const obj = JSON.parse(source); this.setExport('default', obj); }); // Use `module` in linking... </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><code class="language-mjs">import vm from 'node:vm'; const m = new vm.SyntheticModule(['x'], () => { m.setExport('x', 1); }); await m.link(() => {}); await m.evaluate(); assert.strictEqual(m.namespace.x, 1); </code></pre> <pre><code class="language-cjs">const vm = require('node:vm'); (async () => { const m = new vm.SyntheticModule(['x'], () => { m.setExport('x', 1); }); await m.link(() => {}); await m.evaluate(); assert.strictEqual(m.namespace.x, 1); })(); </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> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v18.15.0</td> <td><p>The return value now includes <code>cachedDataRejected</code> with the same semantics as the <code>vm.Script</code> version if the <code>cachedData</code> option was passed.</p> </td></tr> <tr><td>v17.0.0, v16.12.0</td> <td><p>Added support for import attributes 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> </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> {Buffer|TypedArray|DataView} Provides an optional <code>Buffer</code> or <code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied source. This must be produced by a prior call to <a href="#vmcompilefunctioncode-params-options"><code>vm.compileFunction()</code></a> with the same <code>code</code> and <code>params</code>.</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>importAttributes</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-attributes/#sec-evaluate-import-call"><code>optionsExpression</code></a> optional parameter, or an empty object if no value was provided.</li> <li>Returns: {Module Namespace Object|vm.Module} 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> <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> </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">const vm = require('node:vm'); global.globalVar = 3; const context = { globalVar: 1 }; vm.createContext(context); vm.runInContext('globalVar *= 2;', context); console.log(context); // Prints: { globalVar: 2 } console.log(global.globalVar); // Prints: 3 </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><blockquote> <p>Stability: 1 - Experimental</p> </blockquote> <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. Otherwise it will be rejected with an <code>ERR_CONTEXT_NOT_INITIALIZED</code> error.</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">const vm = require('node:vm'); // Measure the memory used by the main context. vm.measureMemory({ mode: 'summary' }) // This is the same as vm.measureMemory() .then((result) => { // The current format is: // { // total: { // jsMemoryEstimate: 2418479, jsMemoryRange: [ 2418479, 2745799 ] // } // } console.log(result); }); const context = vm.createContext({ a: 1 }); vm.measureMemory({ mode: 'detailed', execution: 'eager' }) .then((result) => { // Reference the context here so that it won't be GC'ed // until the measurement is complete. console.log(context.a); // { // total: { // jsMemoryEstimate: 2574732, // jsMemoryRange: [ 2574732, 2904372 ] // }, // current: { // jsMemoryEstimate: 2438996, // jsMemoryRange: [ 2438996, 2768636 ] // }, // other: [ // { // jsMemoryEstimate: 135736, // jsMemoryRange: [ 135736, 465376 ] // } // ] // } console.log(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> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v17.0.0, v16.12.0</td> <td><p>Added support for import attributes 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> </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> {Object|string}<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> {Buffer|TypedArray|DataView} 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>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> {vm.Script}</li> <li><code>importAttributes</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-attributes/#sec-evaluate-import-call"><code>optionsExpression</code></a> optional parameter, or an empty object if no value was provided.</li> <li>Returns: {Module Namespace Object|vm.Module} 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">const vm = require('node:vm'); const contextObject = { globalVar: 1 }; vm.createContext(contextObject); for (let i = 0; i < 10; ++i) { vm.runInContext('globalVar *= 2;', contextObject); } console.log(contextObject); // Prints: { globalVar: 1024 } </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> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v17.0.0, v16.12.0</td> <td><p>Added support for import attributes 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> </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> {Object|string}<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> {Buffer|TypedArray|DataView} 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>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> {vm.Script}</li> <li><code>importAttributes</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-attributes/#sec-evaluate-import-call"><code>optionsExpression</code></a> optional parameter, or an empty object if no value was provided.</li> <li>Returns: {Module Namespace Object|vm.Module} 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">const vm = require('node:vm'); const contextObject = { animal: 'cat', count: 2, }; vm.runInNewContext('count += 1; name = "kitty"', contextObject); console.log(contextObject); // Prints: { animal: 'cat', count: 3, name: 'kitty' } </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> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v17.0.0, v16.12.0</td> <td><p>Added support for import attributes 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> </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> {Object|string}<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> {Buffer|TypedArray|DataView} 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>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> {vm.Script}</li> <li><code>importAttributes</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-attributes/#sec-evaluate-import-call"><code>optionsExpression</code></a> optional parameter, or an empty object if no value was provided.</li> <li>Returns: {Module Namespace Object|vm.Module} 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">const vm = require('node:vm'); let localVar = 'initial value'; const vmResult = vm.runInThisContext('localVar = "vm";'); console.log(`vmResult: '${vmResult}', localVar: '${localVar}'`); // Prints: vmResult: 'vm', localVar: 'initial value' const evalResult = eval('localVar = "eval";'); console.log(`evalResult: '${evalResult}', localVar: '${localVar}'`); // Prints: evalResult: 'eval', localVar: 'eval' </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>node:http</code> module the code passed to the context must either call <code>require('node:http')</code> on its own, or have a reference to the <code>node:http</code> module passed to it. For instance:</p> <pre><code class="language-js">'use strict'; const vm = require('node:vm'); const code = ` ((require) => { const http = require('node: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/'); })`; vm.runInThisContext(code)(require); </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>node: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">const vm = require('node:vm'); function loop() { console.log('entering loop'); while (1) console.log(Date.now()); } vm.runInNewContext( 'Promise.resolve().then(() => loop());', { loop, console }, { timeout: 5 }, ); // This is printed *before* 'entering loop' (!) console.log('done executing'); </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">const vm = require('node:vm'); function loop() { while (1) console.log(Date.now()); } vm.runInNewContext( 'Promise.resolve().then(() => loop());', { loop, console }, { timeout: 5, microtaskMode: 'afterEvaluate' }, ); </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> </body> </html>