{ "source": "doc/api/vm.md", "modules": [ { "textRaw": "VM (Executing JavaScript)", "name": "vm", "stability": 2, "stabilityText": "Stable", "desc": "

You can access this module with:

\n
const vm = require('vm');\n
\n

JavaScript 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.

\n

The options when creating a script are:

\n\n", "signatures": [ { "params": [ { "name": "code" }, { "name": "options" } ] } ] }, { "textRaw": "script.runInContext(contextifiedSandbox[, options])", "type": "method", "name": "runInContext", "meta": { "added": [ "v0.3.1" ] }, "desc": "

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

script.runInContext() takes the same options as\nscript.runInThisContext().

\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
const 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
\n

Note 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", "signatures": [ { "params": [ { "name": "contextifiedSandbox" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "script.runInNewContext([sandbox][, options])", "type": "method", "name": "runInNewContext", "meta": { "added": [ "v0.3.1" ] }, "desc": "

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

script.runInNewContext() takes the same options as\nscript.runInThisContext().

\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
const 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
\n

Note 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", "signatures": [ { "params": [ { "name": "sandbox", "optional": true }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "script.runInThisContext([options])", "type": "method", "name": "runInThisContext", "meta": { "added": [ "v0.3.1" ] }, "desc": "

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

Example of using script.runInThisContext() to compile code once and run it\nmultiple times:

\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\n
\n

The options for running a script are:

\n\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] } ] } ], "methods": [ { "textRaw": "vm.createContext([sandbox])", "type": "method", "name": "createContext", "meta": { "added": [ "v0.3.1" ] }, "desc": "

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

If not given a sandbox object, returns a new, empty contextified sandbox object\nyou can use.

\n

This 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", "signatures": [ { "params": [ { "name": "sandbox", "optional": true } ] } ] }, { "textRaw": "vm.isContext(sandbox)", "type": "method", "name": "isContext", "meta": { "added": [ "v0.11.7" ] }, "desc": "

Returns whether or not a sandbox object has been contextified by calling\nvm.createContext() on it.

\n", "signatures": [ { "params": [ { "name": "sandbox" } ] } ] }, { "textRaw": "vm.runInContext(code, contextifiedSandbox[, options])", "type": "method", "name": "runInContext", "desc": "

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.

\n

vm.runInContext() takes the same options as vm.runInThisContext().

\n

Example: compile and execute different scripts in a single existing context.

\n
const 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
\n

Note 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", "signatures": [ { "params": [ { "name": "code" }, { "name": "contextifiedSandbox" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "vm.runInDebugContext(code)", "type": "method", "name": "runInDebugContext", "meta": { "added": [ "v0.11.14" ] }, "desc": "

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
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
\n

Note 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

The debug object can also be exposed with the --expose_debug_as= switch.

\n", "signatures": [ { "params": [ { "name": "code" } ] } ] }, { "textRaw": "vm.runInNewContext(code[, sandbox][, options])", "type": "method", "name": "runInNewContext", "meta": { "added": [ "v0.3.1" ] }, "desc": "

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

vm.runInNewContext() takes the same options as vm.runInThisContext().

\n

Example: compile and execute code that increments a global variable and sets a\nnew one. These globals are contained in the sandbox.

\n
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

Note 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", "signatures": [ { "params": [ { "name": "code" }, { "name": "sandbox", "optional": true }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "vm.runInThisContext(code[, options])", "type": "method", "name": "runInThisContext", "meta": { "added": [ "v0.3.1" ] }, "desc": "

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

Example of using vm.runInThisContext() and eval() to run the same code:

\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'\n
\n

vm.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

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

Example: Run a Server within a VM

\n

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
'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
\n

Note: 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", "signatures": [ { "params": [ { "name": "code" }, { "name": "options", "optional": true } ] } ] } ], "type": "module", "displayName": "vm" } ] }