{ "source": "doc/api/vm.md", "modules": [ { "textRaw": "VM (Executing JavaScript)", "name": "vm", "stability": 2, "stabilityText": "Stable", "desc": "
You can access this module with:
\nconst vm = require('vm');\n
\nJavaScript code can be compiled and run immediately or compiled, saved, and run\nlater.
\n", "classes": [ { "textRaw": "Class: Script", "type": "class", "name": "Script", "meta": { "added": [ "v0.3.1" ] }, "desc": "A class for holding precompiled scripts, and running them in specific sandboxes.
\n", "methods": [ { "textRaw": "new vm.Script(code, options)", "type": "method", "name": "Script", "meta": { "added": [ "v0.3.1" ] }, "desc": "Creating a new Script
compiles code
but does not run it. Instead, the\ncreated vm.Script
object represents this compiled code. This script can be run\nlater many times using methods below. The returned script is not bound to any\nglobal object. It is bound before each run, just for that run.
The options when creating a script are:
\nfilename
: allows you to control the filename that shows up in any stack\ntraces produced from this script.lineOffset
: allows you to add an offset to the line number that is\ndisplayed in stack tracescolumnOffset
: allows you to add an offset to the column number that is\ndisplayed in stack tracesdisplayErrors
: whether or not to print any errors to stderr, with the\nline of code that caused them highlighted, before throwing an exception.\nApplies only to syntax errors compiling the code; errors while running the\ncode are controlled by the options to the script's methods.timeout
: a number of milliseconds to execute code
before terminating\nexecution. If execution is terminated, an Error
will be thrown.Similar to vm.runInContext()
but a method of a precompiled Script
\nobject. script.runInContext()
runs script
's compiled code in\ncontextifiedSandbox
and returns the result. Running code does not have access\nto local scope.
script.runInContext()
takes the same options as\nscript.runInThisContext()
.
Example: compile code that increments a global variable and sets one, then\nexecute the code multiple times. These globals are contained in the sandbox.
\nconst util = require('util');\nconst vm = require('vm');\n\nvar sandbox = {\n animal: 'cat',\n count: 2\n};\n\nvar context = new vm.createContext(sandbox);\nvar script = new vm.Script('count += 1; name = "kitty"');\n\nfor (var 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 that running untrusted code is a tricky business requiring great care.\nscript.runInContext()
is quite useful, but safely running untrusted code\nrequires a separate process.
Similar to vm.runInNewContext()
but a method of a precompiled Script
\nobject. script.runInNewContext()
contextifies sandbox
if passed or creates a\nnew contextified sandbox if it's omitted, and then runs script
's compiled code\nwith the sandbox as the global object and returns the result. Running code does\nnot have access to local scope.
script.runInNewContext()
takes the same options as\nscript.runInThisContext()
.
Example: compile code that sets a global variable, then execute the code\nmultiple times in different contexts. These globals are set on and contained in\nthe sandboxes.
\nconst util = require('util');\nconst vm = require('vm');\n\nconst sandboxes = [{}, {}, {}];\n\nconst script = new vm.Script('globalVar = "set"');\n\nsandboxes.forEach((sandbox) => {\n script.runInNewContext(sandbox);\n});\n\nconsole.log(util.inspect(sandboxes));\n\n// [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]\n
\nNote that running untrusted code is a tricky business requiring great care.\nscript.runInNewContext()
is quite useful, but safely running untrusted code\nrequires a separate process.
Similar to vm.runInThisContext()
but a method of a precompiled Script
\nobject. script.runInThisContext()
runs script
's compiled code and returns\nthe result. Running code does not have access to local scope, but does have\naccess to the current global
object.
Example of using script.runInThisContext()
to compile code once and run it\nmultiple times:
const vm = require('vm');\n\nglobal.globalVar = 0;\n\nconst script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });\n\nfor (var i = 0; i < 1000; ++i) {\n script.runInThisContext();\n}\n\nconsole.log(globalVar);\n\n// 1000\n
\nThe options for running a script are:
\nfilename
: allows you to control the filename that shows up in any stack\ntraces produced.lineOffset
: allows you to add an offset to the line number that is\ndisplayed in stack tracescolumnOffset
: allows you to add an offset to the column number that is\ndisplayed in stack tracesdisplayErrors
: whether or not to print any errors to stderr, with the\nline of code that caused them highlighted, before throwing an exception.\nApplies only to runtime errors executing the code; it is impossible to create\na Script
instance with syntax errors, as the constructor will throw.timeout
: a number of milliseconds to execute the script before terminating\nexecution. If execution is terminated, an Error
will be thrown.If given a sandbox
object, will "contextify" that sandbox so that it can be\nused in calls to vm.runInContext()
or script.runInContext()
. Inside\nscripts run as such, sandbox
will be the global object, retaining all its\nexisting properties but also having the built-in objects and functions any\nstandard global object has. Outside of scripts run by the vm module,\nsandbox
will be unchanged.
If not given a sandbox object, returns a new, empty contextified sandbox object\nyou can use.
\nThis function is useful for creating a sandbox that can be used to run multiple\nscripts, e.g. if you were emulating a web browser it could be used to create a\nsingle sandbox representing a window's global object, then run all <script>
\ntags together inside that sandbox.
Returns whether or not a sandbox object has been contextified by calling\nvm.createContext()
on it.
vm.runInContext()
compiles code
, then runs it in contextifiedSandbox
and\nreturns the result. Running code does not have access to local scope. The\ncontextifiedSandbox
object must have been previously contextified via\nvm.createContext()
; it will be used as the global object for code
.
vm.runInContext()
takes the same options as vm.runInThisContext()
.
Example: compile and execute different scripts in a single existing context.
\nconst util = require('util');\nconst vm = require('vm');\n\nconst sandbox = { globalVar: 1 };\nvm.createContext(sandbox);\n\nfor (var i = 0; i < 10; ++i) {\n vm.runInContext('globalVar *= 2;', sandbox);\n}\nconsole.log(util.inspect(sandbox));\n\n// { globalVar: 1024 }\n
\nNote that running untrusted code is a tricky business requiring great care.\nvm.runInContext()
is quite useful, but safely running untrusted code requires\na separate process.
vm.runInDebugContext()
compiles and executes code
inside the V8 debug\ncontext. The primary use case is to get 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 that the debug context and object are intrinsically tied to V8's debugger\nimplementation and may change (or even get removed) without prior warning.
\nThe debug object can also be exposed with the --expose_debug_as=
switch.
vm.runInNewContext()
compiles code
, contextifies sandbox
if passed or\ncreates a new contextified sandbox if it's omitted, and then runs the code with\nthe sandbox as the global object and returns the result.
vm.runInNewContext()
takes the same options as vm.runInThisContext()
.
Example: compile and execute code that increments a global variable and sets a\nnew one. These globals are contained in the sandbox.
\nconst 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
\nNote that running untrusted code is a tricky business requiring great care.\nvm.runInNewContext()
is quite useful, but safely running untrusted code requires\na separate process.
vm.runInThisContext()
compiles code
, runs it and returns the result. Running\ncode does not have access to local scope, but does have access to the current\nglobal
object.
Example of using vm.runInThisContext()
and eval()
to run the same code:
const vm = require('vm');\nvar 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
\nvm.runInThisContext()
does not have access to the local scope, so localVar
\nis unchanged. eval()
does have access to the local scope, so localVar
is\nchanged.
In this way vm.runInThisContext()
is much like an indirect eval()
call,\ne.g. (0,eval)('code')
. However, it also has the following additional options:
filename
: allows you to control the filename that shows up in any stack\ntraces produced.lineOffset
: allows you to add an offset to the line number that is\ndisplayed in stack tracescolumnOffset
: allows you to add an offset to the column number that is\ndisplayed in stack tracesdisplayErrors
: whether or not to print any errors to stderr, with the\nline of code that caused them highlighted, before throwing an exception.\nWill capture both syntax errors from compiling code
and runtime errors\nthrown by executing the compiled code. Defaults to true
.timeout
: a number of milliseconds to execute code
before terminating\nexecution. If execution is terminated, an Error
will be thrown.The context of .runInThisContext()
refers to the V8 context. The code passed\nto this VM context will have it's own isolated scope. To run a simple web server\nusing the http
module, for instance, the code passed to the context must either\ncall require('http')
on its own, or have a reference to the http
module passed\nto it. For instance:
'use strict';\nconst vm = require('vm');\n\nlet code =\n`(function(require) {\n\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\n vm.runInThisContext(code)(require);\n
\nNote: require()
in the above case shares the state with context it is passed\nfrom. This might introduce risks when unknown code is executed, e.g. altering\nobjects from the calling thread's context in unwanted ways. It is advisable to\nrun vm
code in a separate process.