<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>VM (Executing JavaScript) | Node.js v6.17.1 Documentation</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic"> <link rel="stylesheet" href="assets/style.css"> <link rel="stylesheet" href="assets/sh.css"> <link rel="canonical" href="https://nodejs.org/api/vm.html"> </head> <body class="alt apidoc" id="api-section-vm"> <div id="content" class="clearfix"> <div id="column2" class="interior"> <div id="intro" class="interior"> <a href="/" title="Go back to the home page"> Node.js </a> </div> <ul> <li><a class="nav-documentation" href="documentation.html">About these Docs</a></li> <li><a class="nav-synopsis" href="synopsis.html">Usage & Example</a></li> </ul> <div class="line"></div> <ul> <li><a class="nav-assert" href="assert.html">Assertion Testing</a></li> <li><a class="nav-buffer" href="buffer.html">Buffer</a></li> <li><a class="nav-addons" href="addons.html">C++ Addons</a></li> <li><a class="nav-n-api" href="n-api.html">C/C++ Addons - N-API</a></li> <li><a class="nav-child_process" href="child_process.html">Child Processes</a></li> <li><a class="nav-cluster" href="cluster.html">Cluster</a></li> <li><a class="nav-cli" href="cli.html">Command Line Options</a></li> <li><a class="nav-console" href="console.html">Console</a></li> <li><a class="nav-crypto" href="crypto.html">Crypto</a></li> <li><a class="nav-debugger" href="debugger.html">Debugger</a></li> <li><a class="nav-dns" href="dns.html">DNS</a></li> <li><a class="nav-domain" href="domain.html">Domain</a></li> <li><a class="nav-errors" href="errors.html">Errors</a></li> <li><a class="nav-events" href="events.html">Events</a></li> <li><a class="nav-fs" href="fs.html">File System</a></li> <li><a class="nav-globals" href="globals.html">Globals</a></li> <li><a class="nav-http" href="http.html">HTTP</a></li> <li><a class="nav-https" href="https.html">HTTPS</a></li> <li><a class="nav-intl" href="intl.html">Internationalization</a></li> <li><a class="nav-modules" href="modules.html">Modules</a></li> <li><a class="nav-net" href="net.html">Net</a></li> <li><a class="nav-os" href="os.html">OS</a></li> <li><a class="nav-path" href="path.html">Path</a></li> <li><a class="nav-process" href="process.html">Process</a></li> <li><a class="nav-punycode" href="punycode.html">Punycode</a></li> <li><a class="nav-querystring" href="querystring.html">Query Strings</a></li> <li><a class="nav-readline" href="readline.html">Readline</a></li> <li><a class="nav-repl" href="repl.html">REPL</a></li> <li><a class="nav-stream" href="stream.html">Stream</a></li> <li><a class="nav-string_decoder" href="string_decoder.html">String Decoder</a></li> <li><a class="nav-timers" href="timers.html">Timers</a></li> <li><a class="nav-tls" href="tls.html">TLS/SSL</a></li> <li><a class="nav-tty" href="tty.html">TTY</a></li> <li><a class="nav-dgram" href="dgram.html">UDP/Datagram</a></li> <li><a class="nav-url" href="url.html">URL</a></li> <li><a class="nav-util" href="util.html">Utilities</a></li> <li><a class="nav-v8" href="v8.html">V8</a></li> <li><a class="nav-vm active" href="vm.html">VM</a></li> <li><a class="nav-zlib" href="zlib.html">ZLIB</a></li> </ul> <div class="line"></div> <ul> <li><a class="nav-https-github-com-nodejs-node" href="https://github.com/nodejs/node">GitHub Repo & Issue Tracker</a></li> <li><a class="nav-http-groups-google-com-group-nodejs" href="http://groups.google.com/group/nodejs">Mailing List</a></li> </ul> </div> <div id="column1" data-id="vm" class="interior"> <header> <h1>Node.js v6.17.1 Documentation</h1> <div id="gtoc"> <ul> <li> <a href="index.html" name="toc">Index</a> </li> <li> <a href="all.html">View on single page</a> </li> <li> <a href="vm.json">View as JSON</a> </li> <li class="version-picker"> <a href="#">View another version <span>▼</span></a> <ol class="version-picker"><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 <b>LTS</b></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 <b>LTS</b></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 <b>LTS</b></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> </li> </ul> </div> <hr> </header> <div id="toc"> <h2>Table of Contents</h2> <ul> <li><span class="stability_2"><a href="#vm_vm_executing_javascript">VM (Executing JavaScript)</a></span><ul> <li><span class="stability_undefined"><a href="#vm_class_vm_script">Class: vm.Script</a></span><ul> <li><span class="stability_undefined"><a href="#vm_new_vm_script_code_options">new vm.Script(code, options)</a></span></li> <li><span class="stability_undefined"><a href="#vm_script_runincontext_contextifiedsandbox_options">script.runInContext(contextifiedSandbox[, options])</a></span></li> <li><span class="stability_undefined"><a href="#vm_script_runinnewcontext_sandbox_options">script.runInNewContext([sandbox][, options])</a></span></li> <li><span class="stability_undefined"><a href="#vm_script_runinthiscontext_options">script.runInThisContext([options])</a></span></li> </ul> </li> <li><span class="stability_undefined"><a href="#vm_vm_createcontext_sandbox">vm.createContext([sandbox])</a></span></li> <li><span class="stability_undefined"><a href="#vm_vm_iscontext_sandbox">vm.isContext(sandbox)</a></span></li> <li><span class="stability_undefined"><a href="#vm_vm_runincontext_code_contextifiedsandbox_options">vm.runInContext(code, contextifiedSandbox[, options])</a></span></li> <li><span class="stability_undefined"><a href="#vm_vm_runindebugcontext_code">vm.runInDebugContext(code)</a></span></li> <li><span class="stability_undefined"><a href="#vm_vm_runinnewcontext_code_sandbox_options">vm.runInNewContext(code[, sandbox][, options])</a></span></li> <li><span class="stability_undefined"><a href="#vm_vm_runinthiscontext_code_options">vm.runInThisContext(code[, options])</a></span></li> <li><span class="stability_undefined"><a href="#vm_example_running_an_http_server_within_a_vm">Example: Running an HTTP Server within a VM</a></span></li> <li><span class="stability_undefined"><a href="#vm_what_does_it_mean_to_contextify_an_object">What does it mean to "contextify" an object?</a></span></li> </ul> </li> </ul> </div> <div id="apicontent"> <h1>VM (Executing JavaScript)<span><a class="mark" href="#vm_vm_executing_javascript"id="vm_vm_executing_javascript">#</a></span></h1> <!--introduced_in=v0.10.0--> <div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><!--name=vm--> <p>The <code>vm</code> module provides APIs for compiling and running code within V8 Virtual Machine contexts.</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 sandboxed environment. The sandboxed code uses a different V8 Context, meaning that it has a different global object than the rest of the code.</p> <p>One can provide the context by <a href="#vm_what_does_it_mean_to_contextify_an_object">"contextifying"</a> a sandbox object. The sandboxed code treats any property on the sandbox like a global variable. Any changes on global variables caused by the sandboxed code are reflected in the sandbox object.</p> <pre><code class="lang-js">const vm = require('vm'); const x = 1; const sandbox = { x: 2 }; vm.createContext(sandbox); // Contextify the sandbox. const code = 'x += 40; var y = 17;'; // x and y are global variables in the sandboxed environment. // Initially, x has the value 2 because that is the value of sandbox.x. vm.runInContext(code, sandbox); console.log(sandbox.x); // 42 console.log(sandbox.y); // 17 console.log(x); // 1; y is not defined. </code></pre> <p><em>Note</em>: The vm module is not a security mechanism. <strong>Do not use it to run untrusted code</strong>.</p> <h2>Class: vm.Script<span><a class="mark" href="#vm_class_vm_script"id="vm_class_vm_script">#</a></span></h2> <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 sandboxes (or "contexts").</p> <h3>new vm.Script(code, options)<span><a class="mark" href="#vm_new_vm_script_code_options"id="vm_new_vm_script_code_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.1</span> </div><ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The JavaScript code to compile.</li> <li><code>options</code><ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the filename used in stack traces produced by this script.</li> <li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the line number offset that is displayed in stack traces produced by this script.</li> <li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the column number offset that is displayed in stack traces produced by this script.</li> <li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, if an <a href="errors.html#errors_class_error"><code>Error</code></a> error occurs while compiling the <code>code</code>, the line of code causing the error is attached to the stack trace.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the number of milliseconds to execute <code>code</code> before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a> will be thrown.</li> <li><code>cachedData</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> Provides an optional <code>Buffer</code> with V8's code cache data for the supplied source. When supplied, the <code>cachedDataRejected</code> value will be set to either <code>true</code> or <code>false</code> depending on acceptance of the data by V8.</li> <li><code>produceCachedData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code> and no <code>cachedData</code> is present, V8 will attempt to produce code cache data for <code>code</code>. Upon success, a <code>Buffer</code> with V8's code cache data will be produced and stored in the <code>cachedData</code> property of the returned <code>vm.Script</code> instance. The <code>cachedDataProduced</code> value will be set to either <code>true</code> or <code>false</code> depending on whether code cache data is produced successfully.</li> </ul> </li> </ul> <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. It is important to note that the <code>code</code> is not bound to any global object; rather, it is bound before each run, just for that run.</p> <h3>script.runInContext(contextifiedSandbox[, options])<span><a class="mark" href="#vm_script_runincontext_contextifiedsandbox_options"id="vm_script_runincontext_contextifiedsandbox_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.1</span> </div><ul> <li><code>contextifiedSandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> object as returned by the <code>vm.createContext()</code> method.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the filename used in stack traces produced by this script.</li> <li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the line number offset that is displayed in stack traces produced by this script.</li> <li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the column number offset that is displayed in stack traces produced by this script.</li> <li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, if an <a href="errors.html#errors_class_error"><code>Error</code></a> error occurs while compiling the <code>code</code>, the line of code causing the error is attached to the stack trace.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the number of milliseconds to execute <code>code</code> before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a> will be thrown.</li> <li><code>breakOnSigint</code>: if <code>true</code>, the execution will be terminated when <code>SIGINT</code> (Ctrl+C) is received. Existing handlers for the event that have been attached via <code>process.on('SIGINT')</code> will be disabled during script execution, but will continue to work after that. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a> will be thrown.</li> </ul> </li> </ul> <p>Runs the compiled code contained by the <code>vm.Script</code> object within the given <code>contextifiedSandbox</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>sandbox</code> object.</p> <pre><code class="lang-js">const util = require('util'); const vm = require('vm'); const sandbox = { animal: 'cat', count: 2 }; const script = new vm.Script('count += 1; name = "kitty";'); const context = vm.createContext(sandbox); for (let i = 0; i < 10; ++i) { script.runInContext(context); } console.log(util.inspect(sandbox)); // { animal: 'cat', count: 12, name: 'kitty' } </code></pre> <p><em>Note</em>: 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> <h3>script.runInNewContext([sandbox][, options])<span><a class="mark" href="#vm_script_runinnewcontext_sandbox_options"id="vm_script_runinnewcontext_sandbox_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.1</span> </div><ul> <li><code>sandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object that will be <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a>. If <code>undefined</code>, a new object will be created.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the filename used in stack traces produced by this script.</li> <li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the line number offset that is displayed in stack traces produced by this script.</li> <li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the column number offset that is displayed in stack traces produced by this script.</li> <li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, if an <a href="errors.html#errors_class_error"><code>Error</code></a> error occurs while compiling the <code>code</code>, the line of code causing the error is attached to the stack trace.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the number of milliseconds to execute <code>code</code> before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a> will be thrown.</li> </ul> </li> </ul> <p>First contextifies the given <code>sandbox</code>, runs the compiled code contained by the <code>vm.Script</code> object within the created sandbox, and returns the result. Running code does not have access to local scope.</p> <p>The following example compiles code that sets a global variable, then executes the code multiple times in different contexts. The globals are set on and contained within each individual <code>sandbox</code>.</p> <pre><code class="lang-js">const util = require('util'); const vm = require('vm'); const script = new vm.Script('globalVar = "set"'); const sandboxes = [{}, {}, {}]; sandboxes.forEach((sandbox) => { script.runInNewContext(sandbox); }); console.log(util.inspect(sandboxes)); // [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] </code></pre> <h3>script.runInThisContext([options])<span><a class="mark" href="#vm_script_runinthiscontext_options"id="vm_script_runinthiscontext_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.1</span> </div><ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the filename used in stack traces produced by this script.</li> <li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the line number offset that is displayed in stack traces produced by this script.</li> <li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the column number offset that is displayed in stack traces produced by this script.</li> <li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, if an <a href="errors.html#errors_class_error"><code>Error</code></a> error occurs while compiling the <code>code</code>, the line of code causing the error is attached to the stack trace.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the number of milliseconds to execute <code>code</code> before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a> will be thrown.</li> </ul> </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="lang-js">const vm = require('vm'); global.globalVar = 0; const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); for (let i = 0; i < 1000; ++i) { script.runInThisContext(); } console.log(globalVar); // 1000 </code></pre> <h2>vm.createContext([sandbox])<span><a class="mark" href="#vm_vm_createcontext_sandbox"id="vm_vm_createcontext_sandbox">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.1</span> </div><ul> <li><code>sandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>If given a <code>sandbox</code> object, the <code>vm.createContext()</code> method will <a href="#vm_what_does_it_mean_to_contextify_an_object">prepare that sandbox</a> so that it can be used in calls to <a href="#vm_vm_runincontext_code_contextifiedsandbox_options"><code>vm.runInContext()</code></a> or <a href="#vm_script_runincontext_contextifiedsandbox_options"><code>script.runInContext()</code></a>. Inside such scripts, the <code>sandbox</code> object will be the global object, retaining all of its existing properties but also having the built-in objects and functions any standard <a href="https://es5.github.io/#x15.1">global object</a> has. Outside of scripts run by the vm module, global variables will remain unchanged.</p> <pre><code class="lang-js">const util = require('util'); const vm = require('vm'); global.globalVar = 3; const sandbox = { globalVar: 1 }; vm.createContext(sandbox); vm.runInContext('globalVar *= 2;', sandbox); console.log(util.inspect(sandbox)); // { globalVar: 2 } console.log(util.inspect(globalVar)); // 3 </code></pre> <p>If <code>sandbox</code> is omitted (or passed explicitly as <code>undefined</code>), a new, empty <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> sandbox object will be returned.</p> <p>The <code>vm.createContext()</code> method is primarily useful for creating a single sandbox that can be used to run multiple scripts. For instance, if emulating a web browser, the method can be used to create a single sandbox representing a window's global object, then run all <code><script></code> tags together within the context of that sandbox.</p> <h2>vm.isContext(sandbox)<span><a class="mark" href="#vm_vm_iscontext_sandbox"id="vm_vm_iscontext_sandbox">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.7</span> </div><ul> <li><code>sandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Returns <code>true</code> if the given <code>sandbox</code> object has been <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> using <a href="#vm_vm_createcontext_sandbox"><code>vm.createContext()</code></a>.</p> <h2>vm.runInContext(code, contextifiedSandbox[, options])<span><a class="mark" href="#vm_vm_runincontext_code_contextifiedsandbox_options"id="vm_vm_runincontext_code_contextifiedsandbox_options">#</a></span></h2> <div class="signature"><ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The JavaScript code to compile and run.</li> <li><code>contextifiedSandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> object that will be used as the <code>global</code> when the <code>code</code> is compiled and run.</li> <li><code>options</code><ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the filename used in stack traces produced by this script.</li> <li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the line number offset that is displayed in stack traces produced by this script.</li> <li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the column number offset that is displayed in stack traces produced by this script.</li> <li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, if an <a href="errors.html#errors_class_error"><code>Error</code></a> error occurs while compiling the <code>code</code>, the line of code causing the error is attached to the stack trace.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the number of milliseconds to execute <code>code</code> before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a> will be thrown.</li> </ul> </li> </ul> </div><p>The <code>vm.runInContext()</code> method compiles <code>code</code>, runs it within the context of the <code>contextifiedSandbox</code>, then returns the result. Running code does not have access to the local scope. The <code>contextifiedSandbox</code> object <em>must</em> have been previously <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> using the <a href="#vm_vm_createcontext_sandbox"><code>vm.createContext()</code></a> method.</p> <p>The following example compiles and executes different scripts using a single <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> object:</p> <pre><code class="lang-js">const util = require('util'); const vm = require('vm'); const sandbox = { globalVar: 1 }; vm.createContext(sandbox); for (let i = 0; i < 10; ++i) { vm.runInContext('globalVar *= 2;', sandbox); } console.log(util.inspect(sandbox)); // { globalVar: 1024 } </code></pre> <h2>vm.runInDebugContext(code)<span><a class="mark" href="#vm_vm_runindebugcontext_code"id="vm_vm_runindebugcontext_code">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.14</span> </div><ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The JavaScript code to compile and run.</li> </ul> <p>The <code>vm.runInDebugContext()</code> method compiles and executes <code>code</code> inside the V8 debug context. The primary use case is to gain access to the V8 <code>Debug</code> object:</p> <pre><code class="lang-js">const vm = require('vm'); const Debug = vm.runInDebugContext('Debug'); console.log(Debug.findScript(process.emit).name); // 'events.js' console.log(Debug.findScript(process.exit).name); // 'internal/process.js' </code></pre> <p><em>Note</em>: The debug context and object are intrinsically tied to V8's debugger implementation and may change (or even be removed) without prior warning.</p> <p>The <code>Debug</code> object can also be made available using the V8-specific <code>--expose_debug_as=</code> <a href="cli.html">command line option</a>.</p> <h2>vm.runInNewContext(code[, sandbox][, options])<span><a class="mark" href="#vm_vm_runinnewcontext_code_sandbox_options"id="vm_vm_runinnewcontext_code_sandbox_options">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.1</span> </div><ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The JavaScript code to compile and run.</li> <li><code>sandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object that will be <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a>. If <code>undefined</code>, a new object will be created.</li> <li><code>options</code><ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the filename used in stack traces produced by this script.</li> <li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the line number offset that is displayed in stack traces produced by this script.</li> <li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the column number offset that is displayed in stack traces produced by this script.</li> <li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, if an <a href="errors.html#errors_class_error"><code>Error</code></a> error occurs while compiling the <code>code</code>, the line of code causing the error is attached to the stack trace.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the number of milliseconds to execute <code>code</code> before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a> will be thrown.</li> </ul> </li> </ul> <p>The <code>vm.runInNewContext()</code> first contextifies the given <code>sandbox</code> object (or creates a new <code>sandbox</code> if passed as <code>undefined</code>), compiles the <code>code</code>, runs it within the context of the created context, then returns the result. Running code does not have access to the local scope.</p> <p>The following example compiles and executes code that increments a global variable and sets a new one. These globals are contained in the <code>sandbox</code>.</p> <pre><code class="lang-js">const util = require('util'); const vm = require('vm'); const sandbox = { animal: 'cat', count: 2 }; vm.runInNewContext('count += 1; name = "kitty"', sandbox); console.log(util.inspect(sandbox)); // { animal: 'cat', count: 3, name: 'kitty' } </code></pre> <h2>vm.runInThisContext(code[, options])<span><a class="mark" href="#vm_vm_runinthiscontext_code_options"id="vm_vm_runinthiscontext_code_options">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.1</span> </div><ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The JavaScript code to compile and run.</li> <li><code>options</code><ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the filename used in stack traces produced by this script.</li> <li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the line number offset that is displayed in stack traces produced by this script.</li> <li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the column number offset that is displayed in stack traces produced by this script.</li> <li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, if an <a href="errors.html#errors_class_error"><code>Error</code></a> error occurs while compiling the <code>code</code>, the line of code causing the error is attached to the stack trace.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the number of milliseconds to execute <code>code</code> before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a> will be thrown.</li> </ul> </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>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="lang-js">const vm = require('vm'); let localVar = 'initial value'; const vmResult = vm.runInThisContext('localVar = "vm";'); console.log('vmResult:', vmResult); console.log('localVar:', localVar); const evalResult = eval('localVar = "eval";'); console.log('evalResult:', evalResult); console.log('localVar:', localVar); // vmResult: 'vm', localVar: 'initial value' // evalResult: 'eval', localVar: 'eval' </code></pre> <p>Because <code>vm.runInThisContext()</code> does not have access to the local scope, <code>localVar</code> is unchanged. In contrast, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval"><code>eval()</code></a> <em>does</em> have access to the local scope, so the value <code>localVar</code> is changed. In this way <code>vm.runInThisContext()</code> is much like an <a href="https://es5.github.io/#x10.4.2">indirect <code>eval()</code> call</a>, e.g. <code>(0,eval)('code')</code>.</p> <h2>Example: Running an HTTP Server within a VM<span><a class="mark" href="#vm_example_running_an_http_server_within_a_vm"id="vm_example_running_an_http_server_within_a_vm">#</a></span></h2> <p>When using either <a href="#vm_script_runinthiscontext_options"><code>script.runInThisContext()</code></a> or <a href="#vm_vm_runinthiscontext_code_options"><code>vm.runInThisContext()</code></a>, the code is executed within the current V8 global context. The code passed to this VM context will have its own isolated scope.</p> <p>In order to run a simple web server using the <code>http</code> module the code passed to the context must either call <code>require('http')</code> on its own, or have a reference to the <code>http</code> module passed to it. For instance:</p> <pre><code class="lang-js">'use strict'; const vm = require('vm'); const code = `((require) => { const http = require('http'); http.createServer( (request, response) => { response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Hello World\\n'); }).listen(8124); console.log('Server running at http://127.0.0.1:8124/'); })`; vm.runInThisContext(code)(require); </code></pre> <p><em>Note</em>: 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> <h2>What does it mean to "contextify" an object?<span><a class="mark" href="#vm_what_does_it_mean_to_contextify_an_object"id="vm_what_does_it_mean_to_contextify_an_object">#</a></span></h2> <p>All JavaScript executed within Node.js runs within the scope of a "context". According to the <a href="https://github.com/v8/v8/wiki/Embedder's%20Guide#contexts">V8 Embedder's Guide</a>:</p> <blockquote> <p>In V8, a context is an execution environment that allows separate, unrelated, JavaScript applications to run in a single instance of V8. You must explicitly specify the context in which you want any JavaScript code to be run.</p> </blockquote> <p>When the method <code>vm.createContext()</code> is called, the <code>sandbox</code> object that is passed in (or a newly created object if <code>sandbox</code> is <code>undefined</code>) is associated internally with a new instance of a V8 Context. This V8 Context provides the <code>code</code> run using the <code>vm</code> modules methods with an isolated global environment within which it can operate. The process of creating the V8 Context and associating it with the <code>sandbox</code> object is what this document refers to as "contextifying" the <code>sandbox</code>.</p> </div> </div> </div> <script src="assets/sh_main.js"></script> <script src="assets/sh_javascript.min.js"></script> <script>highlight(undefined, undefined, 'pre');</script> <!-- __TRACKING__ --> </body> </html>