{ "source": "doc/api/vm.md", "modules": [ { "textRaw": "VM (Executing JavaScript)", "name": "vm", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "
The vm
module provides APIs for compiling and running code within V8 Virtual\nMachine contexts. It can be accessed using:
const vm = require('vm');\n
\nJavaScript code can be compiled and run immediately or compiled, saved, and run\nlater.
\nNote: The vm module is not a security mechanism.\nDo not use it to run untrusted code.
\n", "classes": [ { "textRaw": "Class: vm.Script", "type": "class", "name": "vm.Script", "meta": { "added": [ "v0.3.1" ], "changes": [] }, "desc": "Instances of the vm.Script
class contain precompiled scripts that can be\nexecuted in specific sandboxes (or "contexts").
Creating a new vm.Script
object compiles code
but does not run it. The\ncompiled vm.Script
can be run later multiple times. It is important to note\nthat the code
is not bound to any global object; rather, it is bound before\neach run, just for that run.
Runs the compiled code contained by the vm.Script
object within the given\ncontextifiedSandbox
and returns the result. Running code does not have access\nto local scope.
The following example compiles code that increments a global variable, sets\nthe value of another global variable, then execute the code multiple times.\nThe globals are contained in the sandbox
object.
const util = require('util');\nconst vm = require('vm');\n\nconst sandbox = {\n animal: 'cat',\n count: 2\n};\n\nconst script = new vm.Script('count += 1; name = "kitty";');\n\nconst context = vm.createContext(sandbox);\nfor (let i = 0; i < 10; ++i) {\n script.runInContext(context);\n}\n\nconsole.log(util.inspect(sandbox));\n\n// { animal: 'cat', count: 12, name: 'kitty' }\n
\nNote: Using the timeout
or breakOnSigint
options will result in new\nevent loops and corresponding threads being started, which have a non-zero\nperformance overhead.
First contextifies the given sandbox
, runs the compiled code contained by\nthe vm.Script
object within the created sandbox, and returns the result.\nRunning code does not have access to local scope.
The following example compiles code that sets a global variable, then executes\nthe code multiple times in different contexts. The globals are set on and\ncontained within each individual sandbox
.
const util = require('util');\nconst vm = require('vm');\n\nconst script = new vm.Script('globalVar = "set"');\n\nconst sandboxes = [{}, {}, {}];\nsandboxes.forEach((sandbox) => {\n script.runInNewContext(sandbox);\n});\n\nconsole.log(util.inspect(sandboxes));\n\n// [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]\n
\n"
},
{
"textRaw": "script.runInThisContext([options])",
"type": "method",
"name": "runInThisContext",
"meta": {
"added": [
"v0.3.1"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`options` {Object} ",
"options": [
{
"textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. ",
"name": "filename",
"type": "string",
"desc": "Specifies the filename used in stack traces produced by this script."
},
{
"textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. ",
"name": "lineOffset",
"type": "number",
"desc": "Specifies the line number offset that is displayed in stack traces produced by this script."
},
{
"textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. ",
"name": "columnOffset",
"type": "number",
"desc": "Specifies the column number offset that is displayed in stack traces produced by this script."
},
{
"textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. ",
"name": "displayErrors",
"type": "boolean",
"desc": "When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace."
},
{
"textRaw": "`timeout` {number} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. ",
"name": "timeout",
"type": "number",
"desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown."
}
],
"name": "options",
"type": "Object",
"optional": true
}
]
},
{
"params": [
{
"name": "options",
"optional": true
}
]
}
],
"desc": "Runs the compiled code contained by the vm.Script
within the context of the\ncurrent global
object. Running code does not have access to local scope, but\ndoes have access to the current global
object.
The following example compiles code that increments a global
variable then\nexecutes that code multiple times:
const vm = require('vm');\n\nglobal.globalVar = 0;\n\nconst script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });\n\nfor (let i = 0; i < 1000; ++i) {\n script.runInThisContext();\n}\n\nconsole.log(globalVar);\n\n// 1000\n
\n"
}
]
}
],
"methods": [
{
"textRaw": "vm.createContext([sandbox])",
"type": "method",
"name": "createContext",
"meta": {
"added": [
"v0.3.1"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`sandbox` {Object} ",
"name": "sandbox",
"type": "Object",
"optional": true
}
]
},
{
"params": [
{
"name": "sandbox",
"optional": true
}
]
}
],
"desc": "If given a sandbox
object, the vm.createContext()
method will prepare\nthat sandbox so that it can be used in calls to\nvm.runInContext()
or script.runInContext()
. Inside such scripts,\nthe sandbox
object will be the global object, retaining all of its existing\nproperties but also having the built-in objects and functions any standard\nglobal object has. Outside of scripts run by the vm module, global variables\nwill remain unchanged.
const util = require('util');\nconst vm = require('vm');\n\nglobal.globalVar = 3;\n\nconst sandbox = { globalVar: 1 };\nvm.createContext(sandbox);\n\nvm.runInContext('globalVar *= 2;', sandbox);\n\nconsole.log(util.inspect(sandbox)); // { globalVar: 2 }\n\nconsole.log(util.inspect(globalVar)); // 3\n
\nIf sandbox
is omitted (or passed explicitly as undefined
), a new, empty\ncontextified sandbox object will be returned.
The vm.createContext()
method is primarily useful for creating a single\nsandbox that can be used to run multiple scripts. For instance, if emulating a\nweb browser, the method can be used to create a single sandbox representing a\nwindow's global object, then run all <script>
tags together within the context\nof that sandbox.
Returns true
if the given sandbox
object has been contextified using\nvm.createContext()
.
The vm.runInContext()
method compiles code
, runs it within the context of\nthe contextifiedSandbox
, then returns the result. Running code does not have\naccess to the local scope. The contextifiedSandbox
object must have been\npreviously contextified using the vm.createContext()
method.
The following example compiles and executes different scripts using a single\ncontextified object:
\nconst util = require('util');\nconst vm = require('vm');\n\nconst sandbox = { globalVar: 1 };\nvm.createContext(sandbox);\n\nfor (let i = 0; i < 10; ++i) {\n vm.runInContext('globalVar *= 2;', sandbox);\n}\nconsole.log(util.inspect(sandbox));\n\n// { globalVar: 1024 }\n
\n"
},
{
"textRaw": "vm.runInDebugContext(code)",
"type": "method",
"name": "runInDebugContext",
"meta": {
"added": [
"v0.11.14"
],
"changes": []
},
"stability": 0,
"stabilityText": "Deprecated. An alternative is in development.",
"signatures": [
{
"params": [
{
"textRaw": "`code` {string} The JavaScript code to compile and run. ",
"name": "code",
"type": "string",
"desc": "The JavaScript code to compile and run."
}
]
},
{
"params": [
{
"name": "code"
}
]
}
],
"desc": "The vm.runInDebugContext()
method compiles and executes code
inside the V8\ndebug context. The primary use case is to gain access to the V8 Debug
object:
const vm = require('vm');\nconst Debug = vm.runInDebugContext('Debug');\nconsole.log(Debug.findScript(process.emit).name); // 'events.js'\nconsole.log(Debug.findScript(process.exit).name); // 'internal/process.js'\n
\nNote: The debug context and object are intrinsically tied to V8's debugger\nimplementation and may change (or even be removed) without prior warning.
\nThe Debug
object can also be made available using the V8-specific\n--expose_debug_as=
command line option.
The vm.runInNewContext()
first contextifies the given sandbox
object (or\ncreates a new sandbox
if passed as undefined
), compiles the code
, runs it\nwithin the context of the created context, then returns the result. Running code\ndoes not have access to the local scope.
The following example compiles and executes code that increments a global\nvariable and sets a new one. These globals are contained in the sandbox
.
const util = require('util');\nconst vm = require('vm');\n\nconst sandbox = {\n animal: 'cat',\n count: 2\n};\n\nvm.runInNewContext('count += 1; name = "kitty"', sandbox);\nconsole.log(util.inspect(sandbox));\n\n// { animal: 'cat', count: 3, name: 'kitty' }\n
\n"
},
{
"textRaw": "vm.runInThisContext(code[, options])",
"type": "method",
"name": "runInThisContext",
"meta": {
"added": [
"v0.3.1"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`code` {string} The JavaScript code to compile and run. ",
"name": "code",
"type": "string",
"desc": "The JavaScript code to compile and run."
},
{
"textRaw": "`options` ",
"options": [
{
"textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. ",
"name": "filename",
"type": "string",
"desc": "Specifies the filename used in stack traces produced by this script."
},
{
"textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. ",
"name": "lineOffset",
"type": "number",
"desc": "Specifies the line number offset that is displayed in stack traces produced by this script."
},
{
"textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. ",
"name": "columnOffset",
"type": "number",
"desc": "Specifies the column number offset that is displayed in stack traces produced by this script."
},
{
"textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. ",
"name": "displayErrors",
"type": "boolean",
"desc": "When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace."
},
{
"textRaw": "`timeout` {number} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. ",
"name": "timeout",
"type": "number",
"desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown."
}
],
"name": "options",
"optional": true
}
]
},
{
"params": [
{
"name": "code"
},
{
"name": "options",
"optional": true
}
]
}
],
"desc": "vm.runInThisContext()
compiles code
, runs it within the context of the\ncurrent global
and returns the result. Running code does not have access to\nlocal scope, but does have access to the current global
object.
The following example illustrates using both vm.runInThisContext()
and\nthe JavaScript eval()
function to run the same code:
const vm = require('vm');\nlet localVar = 'initial value';\n\nconst vmResult = vm.runInThisContext('localVar = "vm";');\nconsole.log('vmResult:', vmResult);\nconsole.log('localVar:', localVar);\n\nconst evalResult = eval('localVar = "eval";');\nconsole.log('evalResult:', evalResult);\nconsole.log('localVar:', localVar);\n\n// vmResult: 'vm', localVar: 'initial value'\n// evalResult: 'eval', localVar: 'eval'\n
\nBecause vm.runInThisContext()
does not have access to the local scope,\nlocalVar
is unchanged. In contrast, eval()
does have access to the\nlocal scope, so the value localVar
is changed. In this way\nvm.runInThisContext()
is much like an indirect eval()
call, e.g.\n(0,eval)('code')
.
When using either script.runInThisContext()
or vm.runInThisContext()
, the\ncode is executed within the current V8 global context. The code passed\nto this VM context will have its own isolated scope.
In order to run a simple web server using the http
module the code passed to\nthe context must either call require('http')
on its own, or have a reference\nto the http
module passed to it. For instance:
'use strict';\nconst vm = require('vm');\n\nconst code = `\n(function(require) {\n const http = require('http');\n\n http.createServer((request, response) => {\n response.writeHead(200, { 'Content-Type': 'text/plain' });\n response.end('Hello World\\\\n');\n }).listen(8124);\n\n console.log('Server running at http://127.0.0.1:8124/');\n})`;\n\nvm.runInThisContext(code)(require);\n
\nNote: The require()
in the above case shares the state with the context it\nis passed from. This may introduce risks when untrusted code is executed, e.g.\naltering objects in the context in unwanted ways.
All JavaScript executed within Node.js runs within the scope of a "context".\nAccording to the V8 Embedder's Guide:
\n\n\nIn V8, a context is an execution environment that allows separate, unrelated,\nJavaScript applications to run in a single instance of V8. You must explicitly\nspecify the context in which you want any JavaScript code to be run.
\n
When the method vm.createContext()
is called, the sandbox
object that is\npassed in (or a newly created object if sandbox
is undefined
) is associated\ninternally with a new instance of a V8 Context. This V8 Context provides the\ncode
run using the vm
module's methods with an isolated global environment\nwithin which it can operate. The process of creating the V8 Context and\nassociating it with the sandbox
object is what this document refers to as\n"contextifying" the sandbox
.