Dre4m Shell
Server IP : 85.214.239.14  /  Your IP : 18.220.227.250
Web Server : Apache/2.4.62 (Debian)
System : Linux h2886529.stratoserver.net 4.9.0 #1 SMP Tue Jan 9 19:45:01 MSK 2024 x86_64
User : www-data ( 33)
PHP Version : 7.4.18
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
MySQL : OFF  |  cURL : OFF  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : OFF
Directory :  /proc/2/task/2/cwd/usr/share/doc/nodejs/api/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME SHELL ]     

Current File : /proc/2/task/2/cwd/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="v20.18.0">
  <title>VM (executing JavaScript) | Node.js v20.18.0 Documentation</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback">
  <link rel="stylesheet" href="assets/style.css">
  <link rel="stylesheet" href="assets/hljs.css">
  <link rel="canonical" href="https://nodejs.org/api/vm.html">
  <script async defer src="assets/api.js" type="text/javascript"></script>
  <script>
      const storedTheme = localStorage.getItem('theme');

      // Follow operating system theme preference
      if (storedTheme === null && window.matchMedia) {
        const mq = window.matchMedia('(prefers-color-scheme: dark)');
        if (mq.matches) {
          document.documentElement.classList.add('dark-mode');
        }
      } else if (storedTheme === 'dark') {
        document.documentElement.classList.add('dark-mode');
      }
  </script>
  <style>@media(max-width:462px){.with-30-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:702px){.with-60-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:614px){.with-49-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:686px){.with-58-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}</style>
</head>
<body class="alt apidoc" id="api-section-vm">
  <div id="content" class="clearfix">
    <div role="navigation" id="column2" class="interior">
      <div id="intro" class="interior">
        <a href="/" title="Go back to the home page">
          Node.js
        </a>
      </div>
      <ul>
<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
</ul>
<hr class="line">
<ul>
<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li>
<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
<li><a href="console.html" class="nav-console">Console</a></li>
<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
<li><a href="dns.html" class="nav-dns">DNS</a></li>
<li><a href="domain.html" class="nav-domain">Domain</a></li>
<li><a href="errors.html" class="nav-errors">Errors</a></li>
<li><a href="events.html" class="nav-events">Events</a></li>
<li><a href="fs.html" class="nav-fs">File system</a></li>
<li><a href="globals.html" class="nav-globals">Globals</a></li>
<li><a href="http.html" class="nav-http">HTTP</a></li>
<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
<li><a href="https.html" class="nav-https">HTTPS</a></li>
<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
<li><a href="module.html" class="nav-module">Modules: <code>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 v20.18.0 documentation</h1>
          <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden>
            <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24">
              <path fill="none" d="M0 0h24v24H0z" />
              <path d="M11.1 12.08c-2.33-4.51-.5-8.48.53-10.07C6.27 2.2 1.98 6.59 1.98 12c0 .14.02.28.02.42.62-.27 1.29-.42 2-.42 1.66 0 3.18.83 4.1 2.15A4.01 4.01 0 0111 18c0 1.52-.87 2.83-2.12 3.51.98.32 2.03.5 3.11.5 3.5 0 6.58-1.8 8.37-4.52-2.36.23-6.98-.97-9.26-5.41z"/>
              <path d="M7 16h-.18C6.4 14.84 5.3 14 4 14c-1.66 0-3 1.34-3 3s1.34 3 3 3h3c1.1 0 2-.9 2-2s-.9-2-2-2z"/>
            </svg>
            <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24">
              <path d="M0 0h24v24H0z" fill="none" />
              <path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/>
            </svg>
          </button>
        </div>
        <div id="gtoc">
          <ul>
            <li class="pinned-header">Node.js v20.18.0</li>
            
    <li class="picker-header">
      <a href="#">
        <span class="picker-arrow"></span>
        Table of contents
      </a>

      <div class="picker"><div class="toc"><ul>
<li><span class="stability_2"><a href="#vm-executing-javascript">VM (executing JavaScript)</a></span>
<ul>
<li><a href="#class-vmscript">Class: <code>vm.Script</code></a>
<ul>
<li><a href="#new-vmscriptcode-options"><code>new vm.Script(code[, options])</code></a></li>
<li><a href="#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><span class="stability_1"><a href="#class-vmmodule">Class: <code>vm.Module</code></a></span>
<ul>
<li><a href="#moduledependencyspecifiers"><code>module.dependencySpecifiers</code></a></li>
<li><a href="#moduleerror"><code>module.error</code></a></li>
<li><a href="#moduleevaluateoptions"><code>module.evaluate([options])</code></a></li>
<li><a href="#moduleidentifier"><code>module.identifier</code></a></li>
<li><a href="#modulelinklinker"><code>module.link(linker)</code></a></li>
<li><a href="#modulenamespace"><code>module.namespace</code></a></li>
<li><a href="#modulestatus"><code>module.status</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#class-vmsourcetextmodule">Class: <code>vm.SourceTextModule</code></a></span>
<ul>
<li><a href="#new-vmsourcetextmodulecode-options"><code>new vm.SourceTextModule(code[, options])</code></a></li>
<li><a href="#sourcetextmodulecreatecacheddata"><code>sourceTextModule.createCachedData()</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#class-vmsyntheticmodule">Class: <code>vm.SyntheticModule</code></a></span>
<ul>
<li><a href="#new-vmsyntheticmoduleexportnames-evaluatecallback-options"><code>new vm.SyntheticModule(exportNames, evaluateCallback[, options])</code></a></li>
<li><a href="#syntheticmodulesetexportname-value"><code>syntheticModule.setExport(name, value)</code></a></li>
</ul>
</li>
<li><a href="#vmcompilefunctioncode-params-options"><code>vm.compileFunction(code[, params[, options]])</code></a></li>
<li><a href="#vmconstants"><code>vm.constants</code></a>
<ul>
<li><span class="stability_1"><a href="#vmconstantsuse_main_context_default_loader"><code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code></a></span></li>
</ul>
</li>
<li><a href="#vmcreatecontextcontextobject-options"><code>vm.createContext([contextObject[, options]])</code></a></li>
<li><a href="#vmiscontextobject"><code>vm.isContext(object)</code></a></li>
<li><span class="stability_1"><a href="#vmmeasurememoryoptions"><code>vm.measureMemory([options])</code></a></span></li>
<li><a href="#vmrunincontextcode-contextifiedobject-options"><code>vm.runInContext(code, contextifiedObject[, options])</code></a></li>
<li><a href="#vmruninnewcontextcode-contextobject-options"><code>vm.runInNewContext(code[, contextObject[, options]])</code></a></li>
<li><a href="#vmruninthiscontextcode-options"><code>vm.runInThisContext(code[, options])</code></a></li>
<li><a href="#example-running-an-http-server-within-a-vm">Example: Running an HTTP server within a VM</a></li>
<li><a href="#what-does-it-mean-to-contextify-an-object">What does it mean to "contextify" an object?</a>
<ul>
<li><a href="#vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a></li>
</ul>
</li>
<li><a href="#timeout-interactions-with-asynchronous-tasks-and-promises">Timeout interactions with asynchronous tasks and Promises</a></li>
<li><a href="#support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>
<ul>
<li><a href="#when-the-importmoduledynamically-option-is-not-specified-or-undefined">When the <code>importModuleDynamically</code> option is not specified or undefined</a></li>
<li><a href="#when-importmoduledynamically-is-vmconstantsuse_main_context_default_loader">When <code>importModuleDynamically</code> is <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code></a></li>
<li><a href="#when-importmoduledynamically-is-a-function">When <code>importModuleDynamically</code> is a function</a></li>
</ul>
</li>
</ul>
</li>
</ul></div></div>
    </li>
  
            
    <li class="picker-header">
      <a href="#">
        <span class="picker-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="picker-arrow"></span>
        Other versions
      </a>
      <div class="picker"><ol id="alt-docs"><li><a href="https://nodejs.org/docs/latest-v22.x/api/vm.html">22.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v21.x/api/vm.html">21.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v20.x/api/vm.html">20.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v19.x/api/vm.html">19.x</a></li>
<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</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="picker-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/main/doc/api/vm.md">Edit on GitHub</a></li>    
                </ul>
              </div>
            </li>
          </ul>
        </div>
        <hr>
      </header>

      <details role="navigation" id="toc" open><summary>Table of contents</summary><ul>
<li><span class="stability_2"><a href="#vm-executing-javascript">VM (executing JavaScript)</a></span>
<ul>
<li><a href="#class-vmscript">Class: <code>vm.Script</code></a>
<ul>
<li><a href="#new-vmscriptcode-options"><code>new vm.Script(code[, options])</code></a></li>
<li><a href="#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><span class="stability_1"><a href="#class-vmmodule">Class: <code>vm.Module</code></a></span>
<ul>
<li><a href="#moduledependencyspecifiers"><code>module.dependencySpecifiers</code></a></li>
<li><a href="#moduleerror"><code>module.error</code></a></li>
<li><a href="#moduleevaluateoptions"><code>module.evaluate([options])</code></a></li>
<li><a href="#moduleidentifier"><code>module.identifier</code></a></li>
<li><a href="#modulelinklinker"><code>module.link(linker)</code></a></li>
<li><a href="#modulenamespace"><code>module.namespace</code></a></li>
<li><a href="#modulestatus"><code>module.status</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#class-vmsourcetextmodule">Class: <code>vm.SourceTextModule</code></a></span>
<ul>
<li><a href="#new-vmsourcetextmodulecode-options"><code>new vm.SourceTextModule(code[, options])</code></a></li>
<li><a href="#sourcetextmodulecreatecacheddata"><code>sourceTextModule.createCachedData()</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#class-vmsyntheticmodule">Class: <code>vm.SyntheticModule</code></a></span>
<ul>
<li><a href="#new-vmsyntheticmoduleexportnames-evaluatecallback-options"><code>new vm.SyntheticModule(exportNames, evaluateCallback[, options])</code></a></li>
<li><a href="#syntheticmodulesetexportname-value"><code>syntheticModule.setExport(name, value)</code></a></li>
</ul>
</li>
<li><a href="#vmcompilefunctioncode-params-options"><code>vm.compileFunction(code[, params[, options]])</code></a></li>
<li><a href="#vmconstants"><code>vm.constants</code></a>
<ul>
<li><span class="stability_1"><a href="#vmconstantsuse_main_context_default_loader"><code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code></a></span></li>
</ul>
</li>
<li><a href="#vmcreatecontextcontextobject-options"><code>vm.createContext([contextObject[, options]])</code></a></li>
<li><a href="#vmiscontextobject"><code>vm.isContext(object)</code></a></li>
<li><span class="stability_1"><a href="#vmmeasurememoryoptions"><code>vm.measureMemory([options])</code></a></span></li>
<li><a href="#vmrunincontextcode-contextifiedobject-options"><code>vm.runInContext(code, contextifiedObject[, options])</code></a></li>
<li><a href="#vmruninnewcontextcode-contextobject-options"><code>vm.runInNewContext(code[, contextObject[, options]])</code></a></li>
<li><a href="#vmruninthiscontextcode-options"><code>vm.runInThisContext(code[, options])</code></a></li>
<li><a href="#example-running-an-http-server-within-a-vm">Example: Running an HTTP server within a VM</a></li>
<li><a href="#what-does-it-mean-to-contextify-an-object">What does it mean to "contextify" an object?</a>
<ul>
<li><a href="#vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a></li>
</ul>
</li>
<li><a href="#timeout-interactions-with-asynchronous-tasks-and-promises">Timeout interactions with asynchronous tasks and Promises</a></li>
<li><a href="#support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>
<ul>
<li><a href="#when-the-importmoduledynamically-option-is-not-specified-or-undefined">When the <code>importModuleDynamically</code> option is not specified or undefined</a></li>
<li><a href="#when-importmoduledynamically-is-vmconstantsuse_main_context_default_loader">When <code>importModuleDynamically</code> is <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code></a></li>
<li><a href="#when-importmoduledynamically-is-a-function">When <code>importModuleDynamically</code> is a function</a></li>
</ul>
</li>
</ul>
</li>
</ul></details>

      <div role="main" id="apicontent">
        <h2>VM (executing JavaScript)<span><a class="mark" href="#vm-executing-javascript" id="vm-executing-javascript">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_executing_javascript"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="documentation.html#stability-index">Stability: 2</a> - Stable</div><p></p>

<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/vm.js">lib/vm.js</a></p>
<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"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> x = <span class="hljs-number">1</span>;

<span class="hljs-keyword">const</span> context = { <span class="hljs-attr">x</span>: <span class="hljs-number">2</span> };
vm.<span class="hljs-title function_">createContext</span>(context); <span class="hljs-comment">// Contextify the object.</span>

<span class="hljs-keyword">const</span> code = <span class="hljs-string">'x += 40; var y = 17;'</span>;
<span class="hljs-comment">// `x` and `y` are global variables in the context.</span>
<span class="hljs-comment">// Initially, x has the value 2 because that is the value of context.x.</span>
vm.<span class="hljs-title function_">runInContext</span>(code, context);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">x</span>); <span class="hljs-comment">// 42</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">y</span>); <span class="hljs-comment">// 17</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(x); <span class="hljs-comment">// 1; y is not defined.</span></code> <button class="copy-button">copy</button></pre>
<section><h3>Class: <code>vm.Script</code><span><a class="mark" href="#class-vmscript" id="class-vmscript">#</a></span><a aria-hidden="true" class="legacy" id="vm_class_vm_script"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.1</span>
</div>
<p>Instances of the <code>vm.Script</code> class contain precompiled scripts that can be
executed in specific contexts.</p>
<h4><code>new vm.Script(code[, options])</code><span><a class="mark" href="#new-vmscriptcode-options" id="new-vmscriptcode-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_new_vm_script_code_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</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>v10.6.0</td>
<td><p>The <code>produceCachedData</code> is deprecated in favour of <code>script.createCachedData()</code>.</p></td></tr>
<tr><td>v5.7.0</td>
<td><p>The <code>cachedData</code> and <code>produceCachedData</code> options are supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The JavaScript code to compile.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Specifies the filename used in stack traces produced
by this script. <strong>Default:</strong> <code>'evalmachine.&#x3C;anonymous>'</code>.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;number></a> Specifies the first-line column number offset that
is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>cachedData</code> <a href="buffer.html#class-buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source. When supplied, the <code>cachedDataRejected</code> value will be set to
either <code>true</code> or <code>false</code> depending on acceptance of the data by V8.</li>
<li><code>produceCachedData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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">&#x3C;Function></a> | <a href="vm.html#vmconstantsuse_main_context_default_loader" class="type">&#x3C;vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify how the modules should be loaded during the evaluation
of this script when <code>import()</code> is called. This option is part of the
experimental modules API. We do not recommend using it in a production
environment. For detailed information, see
<a href="#support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</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><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></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">&#x3C;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"><span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">`
function add(a, b) {
  return a + b;
}

const x = add(1, 2);
`</span>);

<span class="hljs-keyword">const</span> cacheWithoutAdd = script.<span class="hljs-title function_">createCachedData</span>();
<span class="hljs-comment">// In `cacheWithoutAdd` the function `add()` is marked for full compilation</span>
<span class="hljs-comment">// upon invocation.</span>

script.<span class="hljs-title function_">runInThisContext</span>();

<span class="hljs-keyword">const</span> cacheWithAdd = script.<span class="hljs-title function_">createCachedData</span>();
<span class="hljs-comment">// `cacheWithAdd` contains fully compiled function `add()`.</span></code> <button class="copy-button">copy</button></pre>
<h4><code>script.runInContext(contextifiedObject[, options])</code><span><a class="mark" href="#scriptrunincontextcontextifiedobject-options" id="scriptrunincontextcontextifiedobject-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_runincontext_contextifiedobject_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>contextifiedObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;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">&#x3C;Object></a>
<ul>
<li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;any></a> the result of the very last statement executed in the script.</li>
</ul>
<p>Runs the compiled code contained by the <code>vm.Script</code> object within the given
<code>contextifiedObject</code> and returns the result. Running code does not have access
to local scope.</p>
<p>The following example compiles code that increments a global variable, sets
the value of another global variable, then execute the code multiple times.
The globals are contained in the <code>context</code> object.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> context = {
  <span class="hljs-attr">animal</span>: <span class="hljs-string">'cat'</span>,
  <span class="hljs-attr">count</span>: <span class="hljs-number">2</span>,
};

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">'count += 1; name = "kitty";'</span>);

vm.<span class="hljs-title function_">createContext</span>(context);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">10</span>; ++i) {
  script.<span class="hljs-title function_">runInContext</span>(context);
}

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context);
<span class="hljs-comment">// Prints: { animal: 'cat', count: 12, name: 'kitty' }</span></code> <button class="copy-button">copy</button></pre>
<p>Using the <code>timeout</code> or <code>breakOnSigint</code> options will result in new event loops
and corresponding threads being started, which have a non-zero performance
overhead.</p>
<h4><code>script.runInNewContext([contextObject[, options]])</code><span><a class="mark" href="#scriptruninnewcontextcontextobject-options" id="scriptruninnewcontextcontextobject-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_runinnewcontext_contextobject_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.0</td>
<td><p>The <code>contextObject</code> argument now accepts <code>vm.constants.DONT_CONTEXTIFY</code>.</p></td></tr>
<tr><td>v14.6.0</td>
<td><p>The <code>microtaskMode</code> option is supported now.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>contextCodeGeneration</code> option is supported now.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>contextObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="vm.html#vmconstantsdont_contextify" class="type">&#x3C;vm.constants.DONT_CONTEXTIFY></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a>
Either <a href="#vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a> or an object that will be <a href="#what-does-it-mean-to-contextify-an-object">contextified</a>.
If <code>undefined</code>, an empty contextified object will be created for backwards compatibility.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;Object></a>
<ul>
<li><code>strings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;any></a> the result of the very last statement executed in the script.</li>
</ul>
<p>This method is a shortcut to <code>script.runInContext(vm.createContext(options), options)</code>.
It does several things at once:</p>
<ol>
<li>Creates a new context.</li>
<li>If <code>contextObject</code> is an object, <a href="#what-does-it-mean-to-contextify-an-object">contextifies</a> it with the new context.
If  <code>contextObject</code> is undefined, creates a new object and <a href="#what-does-it-mean-to-contextify-an-object">contextifies</a> it.
If <code>contextObject</code> is <a href="#vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a>, don't <a href="#what-does-it-mean-to-contextify-an-object">contextify</a> anything.</li>
<li>Runs the compiled code contained by the <code>vm.Script</code> object within the created context. The code
does not have access to the scope in which this method is called.</li>
<li>Returns the result.</li>
</ol>
<p>The following example compiles code that sets a global variable, then executes
the code multiple times in different contexts. The globals are set on and
contained within each individual <code>context</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">'globalVar = "set"'</span>);

<span class="hljs-keyword">const</span> contexts = [{}, {}, {}];
contexts.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  script.<span class="hljs-title function_">runInNewContext</span>(context);
});

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contexts);
<span class="hljs-comment">// Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]</span>

<span class="hljs-comment">// This would throw if the context is created from a contextified object.</span>
<span class="hljs-comment">// vm.constants.DONT_CONTEXTIFY allows creating contexts with ordinary</span>
<span class="hljs-comment">// global objects that can be frozen.</span>
<span class="hljs-keyword">const</span> freezeScript = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">'Object.freeze(globalThis); globalThis;'</span>);
<span class="hljs-keyword">const</span> frozenContext = freezeScript.<span class="hljs-title function_">runInNewContext</span>(vm.<span class="hljs-property">constants</span>.<span class="hljs-property">DONT_CONTEXTIFY</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>script.runInThisContext([options])</code><span><a class="mark" href="#scriptruninthiscontextoptions" id="scriptruninthiscontextoptions">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_runinthiscontext_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;any></a> the result of the very last statement executed in the script.</li>
</ul>
<p>Runs the compiled code contained by the <code>vm.Script</code> within the context of the
current <code>global</code> object. Running code does not have access to local scope, but
<em>does</em> have access to the current <code>global</code> object.</p>
<p>The following example compiles code that increments a <code>global</code> variable then
executes that code multiple times:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-variable language_">global</span>.<span class="hljs-property">globalVar</span> = <span class="hljs-number">0</span>;

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">'globalVar += 1'</span>, { <span class="hljs-attr">filename</span>: <span class="hljs-string">'myfile.vm'</span> });

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">1000</span>; ++i) {
  script.<span class="hljs-title function_">runInThisContext</span>();
}

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(globalVar);

<span class="hljs-comment">// 1000</span></code> <button class="copy-button">copy</button></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: v19.1.0, v18.13.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></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 class="with-30-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">`
function myFunc() {}
//# sourceMappingURL=sourcemap.json
`</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(script.<span class="hljs-property">sourceMapURL</span>);
<span class="hljs-comment">// Prints: sourcemap.json</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">`
function myFunc() {}
//# sourceMappingURL=sourcemap.json
`</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(script.<span class="hljs-property">sourceMapURL</span>);
<span class="hljs-comment">// Prints: sourcemap.json</span></code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>vm.Module</code><span><a class="mark" href="#class-vmmodule" id="class-vmmodule">#</a></span><a aria-hidden="true" class="legacy" id="vm_class_vm_module"></a></h3>
<div class="api_metadata">
<span>Added in: v13.0.0, v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>This feature is only available with the <code>--experimental-vm-modules</code> command
flag enabled.</p>
<p>The <code>vm.Module</code> class provides a low-level interface for using
ECMAScript modules in VM contexts. It is the counterpart of the <code>vm.Script</code>
class that closely mirrors <a href="https://262.ecma-international.org/14.0/#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 class="with-30-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;

<span class="hljs-keyword">const</span> contextifiedObject = vm.<span class="hljs-title function_">createContext</span>({
  <span class="hljs-attr">secret</span>: <span class="hljs-number">42</span>,
  <span class="hljs-attr">print</span>: <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>,
});

<span class="hljs-comment">// Step 1</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Create a Module by constructing a new `vm.SourceTextModule` object. This</span>
<span class="hljs-comment">// parses the provided source text, throwing a `SyntaxError` if anything goes</span>
<span class="hljs-comment">// wrong. By default, a Module is created in the top context. But here, we</span>
<span class="hljs-comment">// specify `contextifiedObject` as the context this Module belongs to.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Here, we attempt to obtain the default export from the module "foo", and</span>
<span class="hljs-comment">// put it into local binding "secret".</span>

<span class="hljs-keyword">const</span> bar = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">`
  import s from 'foo';
  s;
  print(s);
`</span>, { <span class="hljs-attr">context</span>: contextifiedObject });

<span class="hljs-comment">// Step 2</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// "Link" the imported dependencies of this Module to it.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// The provided linking callback (the "linker") accepts two arguments: the</span>
<span class="hljs-comment">// parent module (`bar` in this case) and the string that is the specifier of</span>
<span class="hljs-comment">// the imported module. The callback is expected to return a Module that</span>
<span class="hljs-comment">// corresponds to the provided specifier, with certain requirements documented</span>
<span class="hljs-comment">// in `module.link()`.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// If linking has not started for the returned Module, the same linker</span>
<span class="hljs-comment">// callback will be called on the returned Module.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Even top-level Modules without dependencies must be explicitly linked. The</span>
<span class="hljs-comment">// callback provided would never be called, however.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// The link() method returns a Promise that will be resolved when all the</span>
<span class="hljs-comment">// Promises returned by the linker resolve.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Note: This is a contrived example in that the linker function creates a new</span>
<span class="hljs-comment">// "foo" module every time it is called. In a full-fledged module system, a</span>
<span class="hljs-comment">// cache would probably be used to avoid duplicated modules.</span>

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">linker</span>(<span class="hljs-params">specifier, referencingModule</span>) {
  <span class="hljs-keyword">if</span> (specifier === <span class="hljs-string">'foo'</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">`
      // The "secret" variable refers to the global variable we added to
      // "contextifiedObject" when creating the context.
      export default secret;
    `</span>, { <span class="hljs-attr">context</span>: referencingModule.<span class="hljs-property">context</span> });

    <span class="hljs-comment">// Using `contextifiedObject` instead of `referencingModule.context`</span>
    <span class="hljs-comment">// here would work as well.</span>
  }
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">`Unable to resolve dependency: <span class="hljs-subst">${specifier}</span>`</span>);
}
<span class="hljs-keyword">await</span> bar.<span class="hljs-title function_">link</span>(linker);

<span class="hljs-comment">// Step 3</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Evaluate the Module. The evaluate() method returns a promise which will</span>
<span class="hljs-comment">// resolve after the module has finished evaluating.</span>

<span class="hljs-comment">// Prints 42.</span>
<span class="hljs-keyword">await</span> bar.evaluate();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> contextifiedObject = vm.<span class="hljs-title function_">createContext</span>({
  <span class="hljs-attr">secret</span>: <span class="hljs-number">42</span>,
  <span class="hljs-attr">print</span>: <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>,
});

(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-comment">// Step 1</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// Create a Module by constructing a new `vm.SourceTextModule` object. This</span>
  <span class="hljs-comment">// parses the provided source text, throwing a `SyntaxError` if anything goes</span>
  <span class="hljs-comment">// wrong. By default, a Module is created in the top context. But here, we</span>
  <span class="hljs-comment">// specify `contextifiedObject` as the context this Module belongs to.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// Here, we attempt to obtain the default export from the module "foo", and</span>
  <span class="hljs-comment">// put it into local binding "secret".</span>

  <span class="hljs-keyword">const</span> bar = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">`
    import s from 'foo';
    s;
    print(s);
  `</span>, { <span class="hljs-attr">context</span>: contextifiedObject });

  <span class="hljs-comment">// Step 2</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// "Link" the imported dependencies of this Module to it.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// The provided linking callback (the "linker") accepts two arguments: the</span>
  <span class="hljs-comment">// parent module (`bar` in this case) and the string that is the specifier of</span>
  <span class="hljs-comment">// the imported module. The callback is expected to return a Module that</span>
  <span class="hljs-comment">// corresponds to the provided specifier, with certain requirements documented</span>
  <span class="hljs-comment">// in `module.link()`.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// If linking has not started for the returned Module, the same linker</span>
  <span class="hljs-comment">// callback will be called on the returned Module.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// Even top-level Modules without dependencies must be explicitly linked. The</span>
  <span class="hljs-comment">// callback provided would never be called, however.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// The link() method returns a Promise that will be resolved when all the</span>
  <span class="hljs-comment">// Promises returned by the linker resolve.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// Note: This is a contrived example in that the linker function creates a new</span>
  <span class="hljs-comment">// "foo" module every time it is called. In a full-fledged module system, a</span>
  <span class="hljs-comment">// cache would probably be used to avoid duplicated modules.</span>

  <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">linker</span>(<span class="hljs-params">specifier, referencingModule</span>) {
    <span class="hljs-keyword">if</span> (specifier === <span class="hljs-string">'foo'</span>) {
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">`
        // The "secret" variable refers to the global variable we added to
        // "contextifiedObject" when creating the context.
        export default secret;
      `</span>, { <span class="hljs-attr">context</span>: referencingModule.<span class="hljs-property">context</span> });

      <span class="hljs-comment">// Using `contextifiedObject` instead of `referencingModule.context`</span>
      <span class="hljs-comment">// here would work as well.</span>
    }
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">`Unable to resolve dependency: <span class="hljs-subst">${specifier}</span>`</span>);
  }
  <span class="hljs-keyword">await</span> bar.<span class="hljs-title function_">link</span>(linker);

  <span class="hljs-comment">// Step 3</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// Evaluate the Module. The evaluate() method returns a promise which will</span>
  <span class="hljs-comment">// resolve after the module has finished evaluating.</span>

  <span class="hljs-comment">// Prints 42.</span>
  <span class="hljs-keyword">await</span> bar.evaluate();
})();</code><button class="copy-button">copy</button></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">&#x3C;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">&#x3C;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">&#x3C;Object></a>
<ul>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.10.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>
</tbody></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">&#x3C;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">&#x3C;string></a> The specifier of the requested module:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> foo <span class="hljs-keyword">from</span> <span class="hljs-string">'foo'</span>;
<span class="hljs-comment">//              ^^^^^ the module specifier</span></code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p><code>referencingModule</code> <a href="vm.html#class-vmmodule" class="type">&#x3C;vm.Module></a> 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">&#x3C;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">&#x3C;Object></a> The data from the attribute:
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> foo <span class="hljs-keyword">from</span> <span class="hljs-string">'foo'</span> <span class="hljs-keyword">with</span> { <span class="hljs-attr">name</span>: <span class="hljs-string">'value'</span> };
<span class="hljs-comment">//                         ^^^^^^^^^^^^^^^^^ the attribute</span></code> <button class="copy-button">copy</button></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">&#x3C;Object></a> Alias for <code>extra.attributes</code>.</li>
</ul>
</li>
<li>
<p>Returns: <a href="vm.html#class-vmmodule" class="type">&#x3C;vm.Module></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></p>
</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;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">&#x3C;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">&#x3C;string></a></li>
</ul>
<p>The current status of the module. Will be one of:</p>
<ul>
<li>
<p><code>'unlinked'</code>: <code>module.link()</code> has not yet been called.</p>
</li>
<li>
<p><code>'linking'</code>: <code>module.link()</code> has been called, but not all Promises returned
by the linker function have been resolved yet.</p>
</li>
<li>
<p><code>'linked'</code>: The module has been linked successfully, and all of its
dependencies are linked, but <code>module.evaluate()</code> has not yet been called.</p>
</li>
<li>
<p><code>'evaluating'</code>: The module is being evaluated through a <code>module.evaluate()</code> on
itself or a parent module.</p>
</li>
<li>
<p><code>'evaluated'</code>: The module has been successfully evaluated.</p>
</li>
<li>
<p><code>'errored'</code>: The module has been evaluated, but an exception was thrown.</p>
</li>
</ul>
<p>Other than <code>'errored'</code>, this status string corresponds to the specification's
<a href="https://tc39.es/ecma262/#sec-cyclic-module-records">Cyclic Module Record</a>'s <code>[[Status]]</code> field. <code>'errored'</code> corresponds to
<code>'evaluated'</code> in the specification, but with <code>[[EvaluationError]]</code> set to a
value that is not <code>undefined</code>.</p>
</section><section><h3>Class: <code>vm.SourceTextModule</code><span><a class="mark" href="#class-vmsourcetextmodule" id="class-vmsourcetextmodule">#</a></span><a aria-hidden="true" class="legacy" id="vm_class_vm_sourcetextmodule"></a></h3>
<div class="api_metadata">
<span>Added in: v9.6.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>This feature is only available with the <code>--experimental-vm-modules</code> command
flag enabled.</p>
<ul>
<li>Extends: <a href="vm.html#class-vmmodule" class="type">&#x3C;vm.Module></a></li>
</ul>
<p>The <code>vm.SourceTextModule</code> class provides the <a href="https://tc39.es/ecma262/#sec-source-text-module-records">Source Text Module Record</a> as
defined in the ECMAScript specification.</p>
<h4><code>new vm.SourceTextModule(code[, options])</code><span><a class="mark" href="#new-vmsourcetextmodulecode-options" id="new-vmsourcetextmodulecode-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_new_vm_sourcetextmodule_code_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string></a> String used in stack traces.
<strong>Default:</strong> <code>'vm:module(i)'</code> where <code>i</code> is a context-specific ascending
index.</li>
<li><code>cachedData</code> <a href="buffer.html#class-buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source. The <code>code</code> must be the same as the module from which this
<code>cachedData</code> was created.</li>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;Function></a> Called during evaluation of this <code>Module</code>
to initialize the <code>import.meta</code>.
<ul>
<li><code>meta</code> <a href="esm.html#importmeta" class="type">&#x3C;import.meta></a></li>
<li><code>module</code> <a href="vm.html#class-vmsourcetextmodule" class="type">&#x3C;vm.SourceTextModule></a></li>
</ul>
</li>
<li><code>importModuleDynamically</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Used to specify the
how the modules should be loaded during the evaluation of this module
when <code>import()</code> is called. This option is part of the experimental
modules API. We do not recommend using it in a production environment.
For detailed information, see
<a href="#support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</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 class="with-60-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;

<span class="hljs-keyword">const</span> contextifiedObject = vm.<span class="hljs-title function_">createContext</span>({ <span class="hljs-attr">secret</span>: <span class="hljs-number">42</span> });

<span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(
  <span class="hljs-string">'Object.getPrototypeOf(import.meta.prop).secret = secret;'</span>,
  {
    <span class="hljs-title function_">initializeImportMeta</span>(<span class="hljs-params">meta</span>) {
      <span class="hljs-comment">// Note: this object is created in the top context. As such,</span>
      <span class="hljs-comment">// Object.getPrototypeOf(import.meta.prop) points to the</span>
      <span class="hljs-comment">// Object.prototype in the top context rather than that in</span>
      <span class="hljs-comment">// the contextified object.</span>
      meta.<span class="hljs-property">prop</span> = {};
    },
  });
<span class="hljs-comment">// Since module has no dependencies, the linker function will never be called.</span>
<span class="hljs-keyword">await</span> <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> {});
<span class="hljs-keyword">await</span> <span class="hljs-variable language_">module</span>.evaluate();

<span class="hljs-comment">// Now, Object.prototype.secret will be equal to 42.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// To fix this problem, replace</span>
<span class="hljs-comment">//     meta.prop = {};</span>
<span class="hljs-comment">// above with</span>
<span class="hljs-comment">//     meta.prop = vm.runInContext('{}', contextifiedObject);</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> contextifiedObject = vm.<span class="hljs-title function_">createContext</span>({ <span class="hljs-attr">secret</span>: <span class="hljs-number">42</span> });
(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(
    <span class="hljs-string">'Object.getPrototypeOf(import.meta.prop).secret = secret;'</span>,
    {
      <span class="hljs-title function_">initializeImportMeta</span>(<span class="hljs-params">meta</span>) {
        <span class="hljs-comment">// Note: this object is created in the top context. As such,</span>
        <span class="hljs-comment">// Object.getPrototypeOf(import.meta.prop) points to the</span>
        <span class="hljs-comment">// Object.prototype in the top context rather than that in</span>
        <span class="hljs-comment">// the contextified object.</span>
        meta.<span class="hljs-property">prop</span> = {};
      },
    });
  <span class="hljs-comment">// Since module has no dependencies, the linker function will never be called.</span>
  <span class="hljs-keyword">await</span> <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> {});
  <span class="hljs-keyword">await</span> <span class="hljs-variable language_">module</span>.evaluate();
  <span class="hljs-comment">// Now, Object.prototype.secret will be equal to 42.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// To fix this problem, replace</span>
  <span class="hljs-comment">//     meta.prop = {};</span>
  <span class="hljs-comment">// above with</span>
  <span class="hljs-comment">//     meta.prop = vm.runInContext('{}', contextifiedObject);</span>
})();</code><button class="copy-button">copy</button></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">&#x3C;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"><span class="hljs-comment">// Create an initial module</span>
<span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">'const a = 1;'</span>);

<span class="hljs-comment">// Create cached data from this module</span>
<span class="hljs-keyword">const</span> cachedData = <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">createCachedData</span>();

<span class="hljs-comment">// Create a new module using the cached data. The code must be the same.</span>
<span class="hljs-keyword">const</span> module2 = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">'const a = 1;'</span>, { cachedData });</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>vm.SyntheticModule</code><span><a class="mark" href="#class-vmsyntheticmodule" id="class-vmsyntheticmodule">#</a></span><a aria-hidden="true" class="legacy" id="vm_class_vm_syntheticmodule"></a></h3>
<div class="api_metadata">
<span>Added in: v13.0.0, v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>This feature is only available with the <code>--experimental-vm-modules</code> command
flag enabled.</p>
<ul>
<li>Extends: <a href="vm.html#class-vmmodule" class="type">&#x3C;vm.Module></a></li>
</ul>
<p>The <code>vm.SyntheticModule</code> class provides the <a href="https://heycam.github.io/webidl/#synthetic-module-records">Synthetic Module Record</a> as
defined in the WebIDL specification. The purpose of synthetic modules is to
provide a generic interface for exposing non-JavaScript sources to ECMAScript
module graphs.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> source = <span class="hljs-string">'{ "a": 1 }'</span>;
<span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SyntheticModule</span>([<span class="hljs-string">'default'</span>], <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> obj = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(source);
  <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'default'</span>, obj);
});

<span class="hljs-comment">// Use `module` in linking...</span></code> <button class="copy-button">copy</button></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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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 class="with-30-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;

<span class="hljs-keyword">const</span> m = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SyntheticModule</span>([<span class="hljs-string">'x'</span>], <span class="hljs-function">() =></span> {
  m.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'x'</span>, <span class="hljs-number">1</span>);
});

<span class="hljs-keyword">await</span> m.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> {});
<span class="hljs-keyword">await</span> m.evaluate();

assert.<span class="hljs-title function_">strictEqual</span>(m.<span class="hljs-property">namespace</span>.<span class="hljs-property">x</span>, <span class="hljs-number">1</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">const</span> m = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SyntheticModule</span>([<span class="hljs-string">'x'</span>], <span class="hljs-function">() =></span> {
    m.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'x'</span>, <span class="hljs-number">1</span>);
  });
  <span class="hljs-keyword">await</span> m.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> {});
  <span class="hljs-keyword">await</span> m.evaluate();
  assert.<span class="hljs-title function_">strictEqual</span>(m.<span class="hljs-property">namespace</span>.<span class="hljs-property">x</span>, <span class="hljs-number">1</span>);
})();</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>vm.compileFunction(code[, params[, options]])</code><span><a class="mark" href="#vmcompilefunctioncode-params-options" id="vmcompilefunctioncode-params-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_compilefunction_code_params_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</p></td></tr>
<tr><td>v19.6.0, 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>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;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">&#x3C;Object></a>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;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">&#x3C;number></a> Specifies the first-line column number offset that
is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>cachedData</code> <a href="buffer.html#class-buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source. 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">&#x3C;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">&#x3C;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">&#x3C;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>
</ul>
</li>
<li><code>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="vm.html#vmconstantsuse_main_context_default_loader" class="type">&#x3C;vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify the how the modules should be loaded during the evaluation of
this function when <code>import()</code> is called. This option is part of the
experimental modules API. We do not recommend using it in a production
environment. For detailed information, see
<a href="#support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;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.constants</code><span><a class="mark" href="#vmconstants" id="vmconstants">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_constants"></a></h3>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Returns an object containing commonly used constants for VM operations.</p>
<h4><code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code><span><a class="mark" href="#vmconstantsuse_main_context_default_loader" id="vmconstantsuse_main_context_default_loader">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_constants_use_main_context_default_loader"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>A constant that can be used as the <code>importModuleDynamically</code> option to
<code>vm.Script</code> and <code>vm.compileFunction()</code> so that Node.js uses the default
ESM loader from the main context to load the requested module.</p>
<p>For detailed information, see
<a href="#support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</p>
</section><section><h3><code>vm.createContext([contextObject[, options]])</code><span><a class="mark" href="#vmcreatecontextcontextobject-options" id="vmcreatecontextcontextobject-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_createcontext_contextobject_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.0</td>
<td><p>The <code>contextObject</code> argument now accepts <code>vm.constants.DONT_CONTEXTIFY</code>.</p></td></tr>
<tr><td>v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</p></td></tr>
<tr><td>v20.11.0</td>
<td><p>The <code>importModuleDynamically</code> option is supported now.</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 first argument can no longer be a function.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>codeGeneration</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>contextObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="vm.html#vmconstantsdont_contextify" class="type">&#x3C;vm.constants.DONT_CONTEXTIFY></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a>
Either <a href="#vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a> or an object that will be <a href="#what-does-it-mean-to-contextify-an-object">contextified</a>.
If <code>undefined</code>, an empty contextified object will be created for backwards compatibility.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;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">&#x3C;Object></a>
<ul>
<li><code>strings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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>
<li><code>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="vm.html#vmconstantsuse_main_context_default_loader" class="type">&#x3C;vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify the how the modules should be loaded when <code>import()</code> is
called in this context without a referrer script or module. This option is
part of the experimental modules API. We do not recommend using it in a
production environment. For detailed information, see
<a href="#support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> contextified object.</li>
</ul>
<p>If the given <code>contextObject</code> is an object, the <code>vm.createContext()</code> method will <a href="#what-does-it-mean-to-contextify-an-object">prepare that
object</a> and return a reference to it 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 global object will be wrapped by the <code>contextObject</code>, retaining all of its
existing properties but also having the built-in objects and functions any
standard <a href="https://es5.github.io/#x15.1">global object</a> has. Outside of scripts run by the vm module, global
variables will remain unchanged.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-variable language_">global</span>.<span class="hljs-property">globalVar</span> = <span class="hljs-number">3</span>;

<span class="hljs-keyword">const</span> context = { <span class="hljs-attr">globalVar</span>: <span class="hljs-number">1</span> };
vm.<span class="hljs-title function_">createContext</span>(context);

vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalVar *= 2;'</span>, context);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context);
<span class="hljs-comment">// Prints: { globalVar: 2 }</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-variable language_">global</span>.<span class="hljs-property">globalVar</span>);
<span class="hljs-comment">// Prints: 3</span></code> <button class="copy-button">copy</button></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>When the global object in the newly created context is <a href="#what-does-it-mean-to-contextify-an-object">contextified</a>, it has some quirks
compared to ordinary global objects. For example, it cannot be frozen. To create a context
without the contextifying quirks, pass <a href="#vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a> as the <code>contextObject</code>
argument. See the documentation of <a href="#vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a> for details.</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>&#x3C;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">&#x3C;Object></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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>, or if it's the global object of a context created
using <a href="#vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a>.</p>
</section><section><h3><code>vm.measureMemory([options])</code><span><a class="mark" href="#vmmeasurememoryoptions" id="vmmeasurememoryoptions">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_measurememory_options"></a></h3>
<div class="api_metadata">
<span>Added in: v13.10.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Measure the memory known to V8 and used by all contexts known to the
current V8 isolate, or the main context.</p>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-comment">// Measure the memory used by the main context.</span>
vm.<span class="hljs-title function_">measureMemory</span>({ <span class="hljs-attr">mode</span>: <span class="hljs-string">'summary'</span> })
  <span class="hljs-comment">// This is the same as vm.measureMemory()</span>
  .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
    <span class="hljs-comment">// The current format is:</span>
    <span class="hljs-comment">// {</span>
    <span class="hljs-comment">//   total: {</span>
    <span class="hljs-comment">//      jsMemoryEstimate: 2418479, jsMemoryRange: [ 2418479, 2745799 ]</span>
    <span class="hljs-comment">//    }</span>
    <span class="hljs-comment">// }</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);
  });

<span class="hljs-keyword">const</span> context = vm.<span class="hljs-title function_">createContext</span>({ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> });
vm.<span class="hljs-title function_">measureMemory</span>({ <span class="hljs-attr">mode</span>: <span class="hljs-string">'detailed'</span>, <span class="hljs-attr">execution</span>: <span class="hljs-string">'eager'</span> })
  .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
    <span class="hljs-comment">// Reference the context here so that it won't be GC'ed</span>
    <span class="hljs-comment">// until the measurement is complete.</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">a</span>);
    <span class="hljs-comment">// {</span>
    <span class="hljs-comment">//   total: {</span>
    <span class="hljs-comment">//     jsMemoryEstimate: 2574732,</span>
    <span class="hljs-comment">//     jsMemoryRange: [ 2574732, 2904372 ]</span>
    <span class="hljs-comment">//   },</span>
    <span class="hljs-comment">//   current: {</span>
    <span class="hljs-comment">//     jsMemoryEstimate: 2438996,</span>
    <span class="hljs-comment">//     jsMemoryRange: [ 2438996, 2768636 ]</span>
    <span class="hljs-comment">//   },</span>
    <span class="hljs-comment">//   other: [</span>
    <span class="hljs-comment">//     {</span>
    <span class="hljs-comment">//       jsMemoryEstimate: 135736,</span>
    <span class="hljs-comment">//       jsMemoryRange: [ 135736, 465376 ]</span>
    <span class="hljs-comment">//     }</span>
    <span class="hljs-comment">//   ]</span>
    <span class="hljs-comment">// }</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);
  });</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>vm.runInContext(code, contextifiedObject[, options])</code><span><a class="mark" href="#vmrunincontextcode-contextifiedobject-options" id="vmrunincontextcode-contextifiedobject-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_runincontext_code_contextifiedobject_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</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>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;Object></a> The <a href="#what-does-it-mean-to-contextify-an-object">contextified</a> object that will be used
as the <code>global</code> when the <code>code</code> is compiled and run.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Specifies the filename used in stack traces produced
by this script. <strong>Default:</strong> <code>'evalmachine.&#x3C;anonymous>'</code>.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;boolean></a> If <code>true</code>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <strong>Default:</strong> <code>false</code>.</li>
<li><code>cachedData</code> <a href="buffer.html#class-buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source.</li>
<li><code>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="vm.html#vmconstantsuse_main_context_default_loader" class="type">&#x3C;vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify the how the modules should be loaded during the evaluation
of this script when <code>import()</code> is called. This option is part of the
experimental modules API. We do not recommend using it in a production
environment. For detailed information, see
<a href="#support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
</ul>
</li>
</ul>
<p>The <code>vm.runInContext()</code> method compiles <code>code</code>, runs it within the context of
the <code>contextifiedObject</code>, then returns the result. Running code does not have
access to the local scope. The <code>contextifiedObject</code> object <em>must</em> have been
previously <a href="#what-does-it-mean-to-contextify-an-object">contextified</a> using the <a href="#vmcreatecontextcontextobject-options"><code>vm.createContext()</code></a> method.</p>
<p>If <code>options</code> is a string, then it specifies the filename.</p>
<p>The following example compiles and executes different scripts using a single
<a href="#what-does-it-mean-to-contextify-an-object">contextified</a> object:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> contextObject = { <span class="hljs-attr">globalVar</span>: <span class="hljs-number">1</span> };
vm.<span class="hljs-title function_">createContext</span>(contextObject);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">10</span>; ++i) {
  vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalVar *= 2;'</span>, contextObject);
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contextObject);
<span class="hljs-comment">// Prints: { globalVar: 1024 }</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>vm.runInNewContext(code[, contextObject[, options]])</code><span><a class="mark" href="#vmruninnewcontextcode-contextobject-options" id="vmruninnewcontextcode-contextobject-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_runinnewcontext_code_contextobject_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.0</td>
<td><p>The <code>contextObject</code> argument now accepts <code>vm.constants.DONT_CONTEXTIFY</code>.</p></td></tr>
<tr><td>v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</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>v14.6.0</td>
<td><p>The <code>microtaskMode</code> option is supported now.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>contextCodeGeneration</code> option is supported now.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;Object></a> | <a href="vm.html#vmconstantsdont_contextify" class="type">&#x3C;vm.constants.DONT_CONTEXTIFY></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a>
Either <a href="#vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a> or an object that will be <a href="#what-does-it-mean-to-contextify-an-object">contextified</a>.
If <code>undefined</code>, an empty contextified object will be created for backwards compatibility.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Specifies the filename used in stack traces produced
by this script. <strong>Default:</strong> <code>'evalmachine.&#x3C;anonymous>'</code>.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;Object></a>
<ul>
<li><code>strings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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">&#x3C;boolean></a> If set to false any attempt to compile a WebAssembly
module will throw a <code>WebAssembly.CompileError</code>. <strong>Default:</strong> <code>true</code>.</li>
</ul>
</li>
<li><code>cachedData</code> <a href="buffer.html#class-buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source.</li>
<li><code>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="vm.html#vmconstantsuse_main_context_default_loader" class="type">&#x3C;vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify the how the modules should be loaded during the evaluation
of this script when <code>import()</code> is called. This option is part of the
experimental modules API. We do not recommend using it in a production
environment. For detailed information, see
<a href="#support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
<li><code>microtaskMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;any></a> the result of the very last statement executed in the script.</li>
</ul>
<p>This method is a shortcut to
<code>(new vm.Script(code, options)).runInContext(vm.createContext(options), options)</code>.
If <code>options</code> is a string, then it specifies the filename.</p>
<p>It does several things at once:</p>
<ol>
<li>Creates a new context.</li>
<li>If <code>contextObject</code> is an object, <a href="#what-does-it-mean-to-contextify-an-object">contextifies</a> it with the new context.
If  <code>contextObject</code> is undefined, creates a new object and <a href="#what-does-it-mean-to-contextify-an-object">contextifies</a> it.
If <code>contextObject</code> is <a href="#vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a>, don't <a href="#what-does-it-mean-to-contextify-an-object">contextify</a> anything.</li>
<li>Compiles the code as a<code>vm.Script</code></li>
<li>Runs the compield code within the created context. The code does not have access to the scope in
which this method is called.</li>
<li>Returns the result.</li>
</ol>
<p>The following example compiles and executes code that increments a global
variable and sets a new one. These globals are contained in the <code>contextObject</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> contextObject = {
  <span class="hljs-attr">animal</span>: <span class="hljs-string">'cat'</span>,
  <span class="hljs-attr">count</span>: <span class="hljs-number">2</span>,
};

vm.<span class="hljs-title function_">runInNewContext</span>(<span class="hljs-string">'count += 1; name = "kitty"'</span>, contextObject);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contextObject);
<span class="hljs-comment">// Prints: { animal: 'cat', count: 3, name: 'kitty' }</span>

<span class="hljs-comment">// This would throw if the context is created from a contextified object.</span>
<span class="hljs-comment">// vm.constants.DONT_CONTEXTIFY allows creating contexts with ordinary global objects that</span>
<span class="hljs-comment">// can be frozen.</span>
<span class="hljs-keyword">const</span> frozenContext = vm.<span class="hljs-title function_">runInNewContext</span>(<span class="hljs-string">'Object.freeze(globalThis); globalThis;'</span>, vm.<span class="hljs-property">constants</span>.<span class="hljs-property">DONT_CONTEXTIFY</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>vm.runInThisContext(code[, options])</code><span><a class="mark" href="#vmruninthiscontextcode-options" id="vmruninthiscontextcode-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_runinthiscontext_code_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</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>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The JavaScript code to compile and run.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Specifies the filename used in stack traces produced
by this script. <strong>Default:</strong> <code>'evalmachine.&#x3C;anonymous>'</code>.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;boolean></a> If <code>true</code>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="errors.html#class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <strong>Default:</strong> <code>false</code>.</li>
<li><code>cachedData</code> <a href="buffer.html#class-buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source.</li>
<li><code>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="vm.html#vmconstantsuse_main_context_default_loader" class="type">&#x3C;vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify the how the modules should be loaded during the evaluation
of this script when <code>import()</code> is called. This option is part of the
experimental modules API. We do not recommend using it in a production
environment. For detailed information, see
<a href="#support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> the result of the very last statement executed in the script.</li>
</ul>
<p><code>vm.runInThisContext()</code> compiles <code>code</code>, runs it within the context of the
current <code>global</code> and returns the result. Running code does not have access to
local scope, but does have access to the current <code>global</code> object.</p>
<p>If <code>options</code> is a string, then it specifies the filename.</p>
<p>The following example illustrates using both <code>vm.runInThisContext()</code> and
the JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval"><code>eval()</code></a> function to run the same code:</p>
<!-- eslint-disable prefer-const -->
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">let</span> localVar = <span class="hljs-string">'initial value'</span>;

<span class="hljs-keyword">const</span> vmResult = vm.<span class="hljs-title function_">runInThisContext</span>(<span class="hljs-string">'localVar = "vm";'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`vmResult: '<span class="hljs-subst">${vmResult}</span>', localVar: '<span class="hljs-subst">${localVar}</span>'`</span>);
<span class="hljs-comment">// Prints: vmResult: 'vm', localVar: 'initial value'</span>

<span class="hljs-keyword">const</span> evalResult = <span class="hljs-built_in">eval</span>(<span class="hljs-string">'localVar = "eval";'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`evalResult: '<span class="hljs-subst">${evalResult}</span>', localVar: '<span class="hljs-subst">${localVar}</span>'`</span>);
<span class="hljs-comment">// Prints: evalResult: 'eval', localVar: 'eval'</span></code> <button class="copy-button">copy</button></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"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> code = <span class="hljs-string">`
((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/');
})`</span>;

vm.<span class="hljs-title function_">runInThisContext</span>(code)(<span class="hljs-built_in">require</span>);</code> <button class="copy-button">copy</button></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 with an object, the <code>contextObject</code> argument
will be used to wrap the global object of a new instance of a V8 Context
(if <code>contextObject</code> is <code>undefined</code>, a new object will be created from the current context
before its contextified). 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>
in the outer context is what this document refers to as "contextifying" the object.</p>
<p>The contextifying would introduce some quirks to the <code>globalThis</code> value in the context.
For example, it cannot be frozen, and it is not reference equal to the <code>contextObject</code>
in the outer context.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-comment">// An undefined `contextObject` option makes the global object contextified.</span>
<span class="hljs-keyword">const</span> context = vm.<span class="hljs-title function_">createContext</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalThis'</span>, context) === context);  <span class="hljs-comment">// false</span>
<span class="hljs-comment">// A contextified global object cannot be frozen.</span>
<span class="hljs-keyword">try</span> {
  vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'Object.freeze(globalThis);'</span>, context);
} <span class="hljs-keyword">catch</span> (e) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(e); <span class="hljs-comment">// TypeError: Cannot freeze</span>
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalThis.foo = 1; foo;'</span>, context));  <span class="hljs-comment">// 1</span></code> <button class="copy-button">copy</button></pre>
<p>To create a context with an ordinary global object and get access to a global proxy in
the outer context with fewer quirks, specify <code>vm.constants.DONT_CONTEXTIFY</code> as the
<code>contextObject</code> argument.</p>
<h4><code>vm.constants.DONT_CONTEXTIFY</code><span><a class="mark" href="#vmconstantsdont_contextify" id="vmconstantsdont_contextify">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_constants_dont_contextify"></a></h4>
<p>This constant, when used as the <code>contextObject</code> argument in vm APIs, instructs Node.js to create
a context without wrapping its global object with another object in a Node.js-specific manner.
As a result, the <code>globalThis</code> value inside the new context would behave more closely to an ordinary
one.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-comment">// Use vm.constants.DONT_CONTEXTIFY to freeze the global object.</span>
<span class="hljs-keyword">const</span> context = vm.<span class="hljs-title function_">createContext</span>(vm.<span class="hljs-property">constants</span>.<span class="hljs-property">DONT_CONTEXTIFY</span>);
vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'Object.freeze(globalThis);'</span>, context);
<span class="hljs-keyword">try</span> {
  vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'bar = 1; bar;'</span>, context);
} <span class="hljs-keyword">catch</span> (e) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(e); <span class="hljs-comment">// Uncaught ReferenceError: bar is not defined</span>
}</code> <button class="copy-button">copy</button></pre>
<p>When <code>vm.constants.DONT_CONTEXTIFY</code> is used as the <code>contextObject</code> argument to <a href="#vmcreatecontextcontextobject-options"><code>vm.createContext()</code></a>,
the returned object is a proxy-like object to the global object in the newly created context with
fewer Node.js-specific quirks. It is reference equal to the <code>globalThis</code> value in the new context,
can be modified from outside the context, and can be used to access built-ins in the new context directly.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> context = vm.<span class="hljs-title function_">createContext</span>(vm.<span class="hljs-property">constants</span>.<span class="hljs-property">DONT_CONTEXTIFY</span>);

<span class="hljs-comment">// Returned object is reference equal to globalThis in the new context.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalThis'</span>, context) === context);  <span class="hljs-comment">// true</span>

<span class="hljs-comment">// Can be used to access globals in the new context directly.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">Array</span>);  <span class="hljs-comment">// [Function: Array]</span>
vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'foo = 1;'</span>, context);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">foo</span>);  <span class="hljs-comment">// 1</span>
context.<span class="hljs-property">bar</span> = <span class="hljs-number">1</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'bar;'</span>, context));  <span class="hljs-comment">// 1</span>

<span class="hljs-comment">// Can be frozen and it affects the inner context.</span>
<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">freeze</span>(context);
<span class="hljs-keyword">try</span> {
  vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'baz = 1; baz;'</span>, context);
} <span class="hljs-keyword">catch</span> (e) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(e); <span class="hljs-comment">// Uncaught ReferenceError: baz is not defined</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Timeout interactions with asynchronous tasks and Promises<span><a class="mark" href="#timeout-interactions-with-asynchronous-tasks-and-promises" id="timeout-interactions-with-asynchronous-tasks-and-promises">#</a></span><a aria-hidden="true" class="legacy" id="vm_timeout_interactions_with_asynchronous_tasks_and_promises"></a></h3>
<p><code>Promise</code>s and <code>async function</code>s can schedule tasks run by the JavaScript
engine asynchronously. By default, these tasks are run after all JavaScript
functions on the current stack are done executing.
This allows escaping the functionality of the <code>timeout</code> and
<code>breakOnSigint</code> options.</p>
<p>For example, the following code executed by <code>vm.runInNewContext()</code> with a
timeout of 5 milliseconds schedules an infinite loop to run after a promise
resolves. The scheduled loop is never interrupted by the timeout:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">loop</span>(<span class="hljs-params"></span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'entering loop'</span>);
  <span class="hljs-keyword">while</span> (<span class="hljs-number">1</span>) <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>());
}

vm.<span class="hljs-title function_">runInNewContext</span>(
  <span class="hljs-string">'Promise.resolve().then(() => loop());'</span>,
  { loop, <span class="hljs-variable language_">console</span> },
  { <span class="hljs-attr">timeout</span>: <span class="hljs-number">5</span> },
);
<span class="hljs-comment">// This is printed *before* 'entering loop' (!)</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done executing'</span>);</code> <button class="copy-button">copy</button></pre>
<p>This can be addressed by passing <code>microtaskMode: 'afterEvaluate'</code> to the code
that creates the <code>Context</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">loop</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">while</span> (<span class="hljs-number">1</span>) <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>());
}

vm.<span class="hljs-title function_">runInNewContext</span>(
  <span class="hljs-string">'Promise.resolve().then(() => loop());'</span>,
  { loop, <span class="hljs-variable language_">console</span> },
  { <span class="hljs-attr">timeout</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">microtaskMode</span>: <span class="hljs-string">'afterEvaluate'</span> },
);</code> <button class="copy-button">copy</button></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><section><h3>Support of dynamic <code>import()</code> in compilation APIs<span><a class="mark" href="#support-of-dynamic-import-in-compilation-apis" id="support-of-dynamic-import-in-compilation-apis">#</a></span><a aria-hidden="true" class="legacy" id="vm_support_of_dynamic_import_in_compilation_apis"></a></h3>
<p>The following APIs support an <code>importModuleDynamically</code> option to enable dynamic
<code>import()</code> in code compiled by the vm module.</p>
<ul>
<li><code>new vm.Script</code></li>
<li><code>vm.compileFunction()</code></li>
<li><code>new vm.SourceTextModule</code></li>
<li><code>vm.runInThisContext()</code></li>
<li><code>vm.runInContext()</code></li>
<li><code>vm.runInNewContext()</code></li>
<li><code>vm.createContext()</code></li>
</ul>
<p>This option is still part of the experimental modules API. We do not recommend
using it in a production environment.</p>
<h4>When the <code>importModuleDynamically</code> option is not specified or undefined<span><a class="mark" href="#when-the-importmoduledynamically-option-is-not-specified-or-undefined" id="when-the-importmoduledynamically-option-is-not-specified-or-undefined">#</a></span><a aria-hidden="true" class="legacy" id="vm_when_the_importmoduledynamically_option_is_not_specified_or_undefined"></a></h4>
<p>If this option is not specified, or if it's <code>undefined</code>, code containing
<code>import()</code> can still be compiled by the vm APIs, but when the compiled code is
executed and it actually calls <code>import()</code>, the result will reject with
<a href="errors.html#err_vm_dynamic_import_callback_missing"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code></a>.</p>
<h4>When <code>importModuleDynamically</code> is <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code><span><a class="mark" href="#when-importmoduledynamically-is-vmconstantsuse_main_context_default_loader" id="when-importmoduledynamically-is-vmconstantsuse_main_context_default_loader">#</a></span><a aria-hidden="true" class="legacy" id="vm_when_importmoduledynamically_is_vm_constants_use_main_context_default_loader"></a></h4>
<p>This option is currently not supported for <code>vm.SourceTextModule</code>.</p>
<p>With this option, when an <code>import()</code> is initiated in the compiled code, Node.js
would use the default ESM loader from the main context to load the requested
module and return it to the code being executed.</p>
<p>This gives access to Node.js built-in modules such as <code>fs</code> or <code>http</code>
to the code being compiled. If the code is executed in a different context,
be aware that the objects created by modules loaded from the main context
are still from the main context and not <code>instanceof</code> built-in classes in the
new context.</p>

<pre class="with-49-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Script</span>, constants } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(
  <span class="hljs-string">'import("node:fs").then(({readFile}) => readFile instanceof Function)'</span>,
  { <span class="hljs-attr">importModuleDynamically</span>: constants.<span class="hljs-property">USE_MAIN_CONTEXT_DEFAULT_LOADER</span> });

<span class="hljs-comment">// false: URL loaded from the main context is not an instance of the Function</span>
<span class="hljs-comment">// class in the new context.</span>
script.<span class="hljs-title function_">runInNewContext</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Script</span>, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(
  <span class="hljs-string">'import("node:fs").then(({readFile}) => readFile instanceof Function)'</span>,
  { <span class="hljs-attr">importModuleDynamically</span>: constants.<span class="hljs-property">USE_MAIN_CONTEXT_DEFAULT_LOADER</span> });

<span class="hljs-comment">// false: URL loaded from the main context is not an instance of the Function</span>
<span class="hljs-comment">// class in the new context.</span>
script.<span class="hljs-title function_">runInNewContext</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><button class="copy-button">copy</button></pre>
<p>This option also allows the script or function to load user modules:</p>

<pre class="with-49-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Script</span>, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;
<span class="hljs-keyword">import</span> { resolve } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;
<span class="hljs-keyword">import</span> { writeFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-comment">// Write test.js and test.txt to the directory where the current script</span>
<span class="hljs-comment">// being run is located.</span>
<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-title function_">resolve</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">dirname</span>, <span class="hljs-string">'test.mjs'</span>),
              <span class="hljs-string">'export const filename = "./test.json";'</span>);
<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-title function_">resolve</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">dirname</span>, <span class="hljs-string">'test.json'</span>),
              <span class="hljs-string">'{"hello": "world"}'</span>);

<span class="hljs-comment">// Compile a script that loads test.mjs and then test.json</span>
<span class="hljs-comment">// as if the script is placed in the same directory.</span>
<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(
  <span class="hljs-string">`(async function() {
    const { filename } = await import('./test.mjs');
    return import(filename, { with: { type: 'json' } })
  })();`</span>,
  {
    <span class="hljs-attr">filename</span>: <span class="hljs-title function_">resolve</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">dirname</span>, <span class="hljs-string">'test-with-default.js'</span>),
    <span class="hljs-attr">importModuleDynamically</span>: constants.<span class="hljs-property">USE_MAIN_CONTEXT_DEFAULT_LOADER</span>,
  });

<span class="hljs-comment">// { default: { hello: 'world' } }</span>
script.<span class="hljs-title function_">runInThisContext</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Script</span>, constants } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> { resolve } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);
<span class="hljs-keyword">const</span> { writeFileSync } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-comment">// Write test.js and test.txt to the directory where the current script</span>
<span class="hljs-comment">// being run is located.</span>
<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-title function_">resolve</span>(__dirname, <span class="hljs-string">'test.mjs'</span>),
              <span class="hljs-string">'export const filename = "./test.json";'</span>);
<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-title function_">resolve</span>(__dirname, <span class="hljs-string">'test.json'</span>),
              <span class="hljs-string">'{"hello": "world"}'</span>);

<span class="hljs-comment">// Compile a script that loads test.mjs and then test.json</span>
<span class="hljs-comment">// as if the script is placed in the same directory.</span>
<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(
  <span class="hljs-string">`(async function() {
    const { filename } = await import('./test.mjs');
    return import(filename, { with: { type: 'json' } })
  })();`</span>,
  {
    <span class="hljs-attr">filename</span>: <span class="hljs-title function_">resolve</span>(__dirname, <span class="hljs-string">'test-with-default.js'</span>),
    <span class="hljs-attr">importModuleDynamically</span>: constants.<span class="hljs-property">USE_MAIN_CONTEXT_DEFAULT_LOADER</span>,
  });

<span class="hljs-comment">// { default: { hello: 'world' } }</span>
script.<span class="hljs-title function_">runInThisContext</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><button class="copy-button">copy</button></pre>
<p>There are a few caveats with loading user modules using the default loader
from the main context:</p>
<ol>
<li>The module being resolved would be relative to the <code>filename</code> option passed
to <code>vm.Script</code> or <code>vm.compileFunction()</code>. The resolution can work with a
<code>filename</code> that's either an absolute path or a URL string.  If <code>filename</code> is
a string that's neither an absolute path or a URL, or if it's undefined,
the resolution will be relative to the current working directory
of the process. In the case of <code>vm.createContext()</code>, the resolution is always
relative to the current working directory since this option is only used when
there isn't a referrer script or module.</li>
<li>For any given <code>filename</code> that resolves to a specific path, once the process
manages to load a particular module from that path, the result may be cached,
and subsequent load of the same module from the same path would return the
same thing. If the <code>filename</code> is a URL string, the cache would not be hit
if it has different search parameters. For <code>filename</code>s that are not URL
strings, there is currently no way to bypass the caching behavior.</li>
</ol>
<h4>When <code>importModuleDynamically</code> is a function<span><a class="mark" href="#when-importmoduledynamically-is-a-function" id="when-importmoduledynamically-is-a-function">#</a></span><a aria-hidden="true" class="legacy" id="vm_when_importmoduledynamically_is_a_function"></a></h4>
<p>When <code>importModuleDynamically</code> is a function, it will be invoked when <code>import()</code>
is called in the compiled code for users to customize how the requested module
should be compiled and evaluated. Currently, the Node.js instance must be
launched with the <code>--experimental-vm-modules</code> flag for this option to work. If
the flag isn't set, this callback will be ignored. If the code evaluated
actually calls to <code>import()</code>, the result will reject with
<a href="errors.html#err_vm_dynamic_import_callback_missing_flag"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG</code></a>.</p>
<p>The callback <code>importModuleDynamically(specifier, referrer, importAttributes)</code>
has the following signature:</p>
<ul>
<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> specifier passed to <code>import()</code></li>
<li><code>referrer</code> <a href="vm.html#class-vmscript" class="type">&#x3C;vm.Script></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="vm.html#class-vmsourcetextmodule" class="type">&#x3C;vm.SourceTextModule></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
The referrer is the compiled <code>vm.Script</code> for <code>new vm.Script</code>,
<code>vm.runInThisContext</code>, <code>vm.runInContext</code> and <code>vm.runInNewContext</code>. It's the
compiled <code>Function</code> for <code>vm.compileFunction</code>, the compiled
<code>vm.SourceTextModule</code> for <code>new vm.SourceTextModule</code>, and the context <code>Object</code>
for <code>vm.createContext()</code>.</li>
<li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The <code>"with"</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: <a href="https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects" class="type">&#x3C;Module Namespace Object></a> | <a href="vm.html#class-vmmodule" class="type">&#x3C;vm.Module></a> Returning a <code>vm.Module</code> is
recommended in order to take advantage of error tracking, and to avoid issues
with namespaces that contain <code>then</code> function exports.</li>
</ul>

<pre class="with-58-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// This script must be run with --experimental-vm-modules.</span>
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Script</span>, <span class="hljs-title class_">SyntheticModule</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(<span class="hljs-string">'import("foo.json", { with: { type: "json" } })'</span>, {
  <span class="hljs-keyword">async</span> <span class="hljs-title function_">importModuleDynamically</span>(<span class="hljs-params">specifier, referrer, importAttributes</span>) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(specifier);  <span class="hljs-comment">// 'foo.json'</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(referrer);   <span class="hljs-comment">// The compiled script</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(importAttributes);  <span class="hljs-comment">// { type: 'json' }</span>
    <span class="hljs-keyword">const</span> m = <span class="hljs-keyword">new</span> <span class="hljs-title class_">SyntheticModule</span>([<span class="hljs-string">'bar'</span>], <span class="hljs-function">() =></span> { });
    <span class="hljs-keyword">await</span> m.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> { });
    m.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'bar'</span>, { <span class="hljs-attr">hello</span>: <span class="hljs-string">'world'</span> });
    <span class="hljs-keyword">return</span> m;
  },
});
<span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> script.<span class="hljs-title function_">runInThisContext</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);  <span class="hljs-comment">//  { bar: { hello: 'world' } }</span></code><code class="language-js cjs"><span class="hljs-comment">// This script must be run with --experimental-vm-modules.</span>
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Script</span>, <span class="hljs-title class_">SyntheticModule</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">main</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(<span class="hljs-string">'import("foo.json", { with: { type: "json" } })'</span>, {
    <span class="hljs-keyword">async</span> <span class="hljs-title function_">importModuleDynamically</span>(<span class="hljs-params">specifier, referrer, importAttributes</span>) {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(specifier);  <span class="hljs-comment">// 'foo.json'</span>
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(referrer);   <span class="hljs-comment">// The compiled script</span>
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(importAttributes);  <span class="hljs-comment">// { type: 'json' }</span>
      <span class="hljs-keyword">const</span> m = <span class="hljs-keyword">new</span> <span class="hljs-title class_">SyntheticModule</span>([<span class="hljs-string">'bar'</span>], <span class="hljs-function">() =></span> { });
      <span class="hljs-keyword">await</span> m.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> { });
      m.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'bar'</span>, { <span class="hljs-attr">hello</span>: <span class="hljs-string">'world'</span> });
      <span class="hljs-keyword">return</span> m;
    },
  });
  <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> script.<span class="hljs-title function_">runInThisContext</span>();
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);  <span class="hljs-comment">//  { bar: { hello: 'world' } }</span>
})();</code><button class="copy-button">copy</button></pre></section>
        <!-- API END -->
      </div>
    </div>
  </div>
</body>
</html>

Anon7 - 2022
AnonSec Team