{ "source": "doc/api/vm.md", "modules": [ { "textRaw": "Executing JavaScript", "name": "vm", "stability": 2, "stabilityText": "Stable", "desc": "
You can access this module with:\n\n
\nconst vm = require('vm');
\nJavaScript code can be compiled and run immediately or compiled, saved, and run\nlater.\n\n
\n", "classes": [ { "textRaw": "Class: Script", "type": "class", "name": "Script", "desc": "A class for holding precompiled scripts, and running them in specific sandboxes.\n\n
\n", "methods": [ { "textRaw": "new vm.Script(code, options)", "type": "method", "name": "Script", "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.\n\n
The options when creating a script are:\n\n
\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
: if true
, on error, attach the line of code that caused\nthe error to the stack trace. Applies only to syntax errors compiling the\ncode; errors while running the code are controlled by the options to the\nscript's methods.timeout
: a number of milliseconds to execute code
before terminating\nexecution. If execution is terminated, an [Error
][] will be thrown.cachedData
: an optional Buffer
with V8's code cache data for the supplied\nsource. When supplied cachedDataRejected
value will be set to either\ntrue
or false
depending on acceptance of the data by V8.produceCachedData
: if true
and no cachedData
is present - V8 tries to\nproduce code cache data for code
. Upon success, a Buffer
with V8's code\ncache data will be produced and stored in cachedData
property of the\nreturned vm.Script
instance. cachedDataProduced
value will be set to\neither true
or false
depending on whether code cache data is produced\nsuccessfully.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.\n\n
script.runInContext()
takes the same options as\n[script.runInThisContext()
][].\n\n
Example: compile code that increments a global variable and sets one, then\nexecute the code multiple times. These globals are contained in the sandbox.\n\n
\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' }
\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.\n\n
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.\n\n
script.runInNewContext()
takes the same options as\n[script.runInThisContext()
][].\n\n
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.\n\n
\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' }]
\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.\n\n
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.\n\n
Example of using script.runInThisContext()
to compile code once and run it\nmultiple times:\n\n
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
\nThe options for running a script are:\n\n
\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
: if true
, on error, attach the line of code that caused\nthe error to the stack trace. Applies only to runtime errors executing the\ncode; it is impossible to create a Script
instance with syntax errors, as\nthe 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.\n\n
If not given a sandbox object, returns a new, empty contextified sandbox object\nyou can use.\n\n
\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.\n\n
Returns whether or not a sandbox object has been contextified by calling\n[vm.createContext()
][] on it.\n\n
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\n[vm.createContext()
][]; it will be used as the global object for code
.\n\n
vm.runInContext()
takes the same options as [vm.runInThisContext()
][].\n\n
Example: compile and execute different scripts in a single existing context.\n\n
\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 }
\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.\n\n
vm.runInDebugContext()
compiles and executes code
inside the V8 debug\ncontext. The primary use case is to get access to the V8 debug object:\n\n
const Debug = vm.runInDebugContext('Debug');\nDebug.scripts().forEach((script) => { console.log(script.name); });
\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.\n\n
\nThe debug object can also be exposed with the --expose_debug_as=
switch.\n\n
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.\n\n
vm.runInNewContext()
takes the same options as [vm.runInThisContext()
][].\n\n
Example: compile and execute code that increments a global variable and sets a\nnew one. These globals are contained in the sandbox.\n\n
\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' }
\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.\n\n
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.\n\n
Example of using vm.runInThisContext()
and [eval()
][] to run the same code:\n\n
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'
\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.\n\n
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:\n\n
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
: if true
, on error, attach the line of code that caused\nthe error to the stack trace. Will capture both syntax errors from compiling\ncode
and runtime errors thrown by executing the compiled code. Defaults to\ntrue
.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:\n\n
'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);
\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.\n\n