7 You can access this module with:
9 var vm = require('vm');
11 JavaScript code can be compiled and run immediately or compiled, saved, and run
16 A class for holding precompiled scripts, and running them in specific sandboxes.
18 ### new vm.Script(code, options)
20 Creating a new `Script` compiles `code` but does not run it. Instead, the
21 created `vm.Script` object represents this compiled code. This script can be run
22 later many times using methods below. The returned script is not bound to any
23 global object. It is bound before each run, just for that run.
25 The options when creating a script are:
27 - `filename`: allows you to control the filename that shows up in any stack
28 traces produced from this script.
29 - `displayErrors`: whether or not to print any errors to stderr, with the
30 line of code that caused them highlighted, before throwing an exception.
31 Applies only to syntax errors compiling the code; errors while running the
32 code are controlled by the options to the script's methods.
34 ### script.runInContext(contextifiedSandbox[, options])
36 Similar to `vm.runInContext` but a method of a precompiled `Script` object.
37 `script.runInContext` runs `script`'s compiled code in `contextifiedSandbox`
38 and returns the result. Running code does not have access to local scope.
40 `script.runInContext` takes the same options as `script.runInThisContext`.
42 Example: compile code that increments a global variable and sets one, then
43 execute the code multiple times. These globals are contained in the sandbox.
45 var util = require('util');
46 var vm = require('vm');
53 var context = new vm.createContext(sandbox);
54 var script = new vm.Script('count += 1; name = "kitty"');
56 for (var i = 0; i < 10; ++i) {
57 script.runInContext(context);
60 console.log(util.inspect(sandbox));
62 // { animal: 'cat', count: 12, name: 'kitty' }
64 Note that running untrusted code is a tricky business requiring great care.
65 `script.runInContext` is quite useful, but safely running untrusted code
66 requires a separate process.
68 ### script.runInNewContext([sandbox][, options])
70 Similar to `vm.runInNewContext` but a method of a precompiled `Script` object.
71 `script.runInNewContext` contextifies `sandbox` if passed or creates a new
72 contextified sandbox if it's omitted, and then runs `script`'s compiled code
73 with the sandbox as the global object and returns the result. Running code does
74 not have access to local scope.
76 `script.runInNewContext` takes the same options as `script.runInThisContext`.
78 Example: compile code that sets a global variable, then execute the code
79 multiple times in different contexts. These globals are set on and contained in
82 var util = require('util');
83 var vm = require('vm');
85 var sandboxes = [{}, {}, {}];
87 var script = new vm.Script('globalVar = "set"');
89 sandboxes.forEach(function (sandbox) {
90 script.runInNewContext(sandbox);
93 console.log(util.inspect(sandboxes));
95 // [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]
97 Note that running untrusted code is a tricky business requiring great care.
98 `script.runInNewContext` is quite useful, but safely running untrusted code
99 requires a separate process.
101 ### script.runInThisContext([options])
103 Similar to `vm.runInThisContext` but a method of a precompiled `Script` object.
104 `script.runInThisContext` runs `script`'s compiled code and returns the result.
105 Running code does not have access to local scope, but does have access to the
106 current `global` object.
108 Example of using `script.runInThisContext` to compile code once and run it
111 var vm = require('vm');
113 global.globalVar = 0;
115 var script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });
117 for (var i = 0; i < 1000; ++i) {
118 script.runInThisContext();
121 console.log(globalVar);
125 The options for running a script are:
127 - `displayErrors`: whether or not to print any runtime errors to stderr, with
128 the line of code that caused them highlighted, before throwing an exception.
129 Applies only to runtime errors executing the code; it is impossible to create
130 a `Script` instance with syntax errors, as the constructor will throw.
131 - `timeout`: a number of milliseconds to execute the script before terminating
132 execution. If execution is terminated, an `Error` will be thrown.
134 ## vm.createContext([sandbox])
136 If given a `sandbox` object, will "contextify" that sandbox so that it can be
137 used in calls to `vm.runInContext` or `script.runInContext`. Inside scripts run
138 as such, `sandbox` will be the global object, retaining all its existing
139 properties but also having the built-in objects and functions any standard
140 [global object][2] has. Outside of scripts run by the vm module, `sandbox` will
143 If not given a sandbox object, returns a new, empty contextified sandbox object
146 This function is useful for creating a sandbox that can be used to run multiple
147 scripts, e.g. if you were emulating a web browser it could be used to create a
148 single sandbox representing a window's global object, then run all `<script>`
149 tags together inside that sandbox.
151 [2]: http://es5.github.io/#x15.1
153 ## vm.isContext(sandbox)
155 Returns whether or not a sandbox object has been contextified by calling
156 `vm.createContext` on it.
158 ## vm.runInContext(code, contextifiedSandbox[, options])
160 `vm.runInContext` compiles `code`, then runs it in `contextifiedSandbox` and
161 returns the result. Running code does not have access to local scope. The
162 `contextifiedSandbox` object must have been previously contextified via
163 `vm.createContext`; it will be used as the global object for `code`.
165 `vm.runInContext` takes the same options as `vm.runInThisContext`.
167 Example: compile and execute different scripts in a single existing context.
169 var util = require('util');
170 var vm = require('vm');
172 var sandbox = { globalVar: 1 };
173 vm.createContext(sandbox);
175 for (var i = 0; i < 10; ++i) {
176 vm.runInContext('globalVar *= 2;', sandbox);
178 console.log(util.inspect(sandbox));
180 // { globalVar: 1024 }
182 Note that running untrusted code is a tricky business requiring great care.
183 `vm.runInContext` is quite useful, but safely running untrusted code requires a
186 ## vm.runInDebugContext(code)
188 `vm.runInDebugContext` compiles and executes `code` inside the V8 debug context.
189 The primary use case is to get access to the V8 debug object:
191 var Debug = vm.runInDebugContext('Debug');
192 Debug.scripts().forEach(function(script) { console.log(script.name); });
194 Note that the debug context and object are intrinsically tied to V8's debugger
195 implementation and may change (or even get removed) without prior warning.
197 The debug object can also be exposed with the `--expose_debug_as=` switch.
199 ## vm.runInNewContext(code[, sandbox][, options])
201 `vm.runInNewContext` compiles `code`, contextifies `sandbox` if passed or
202 creates a new contextified sandbox if it's omitted, and then runs the code with
203 the sandbox as the global object and returns the result.
205 `vm.runInNewContext` takes the same options as `vm.runInThisContext`.
207 Example: compile and execute code that increments a global variable and sets a
208 new one. These globals are contained in the sandbox.
210 var util = require('util');
211 var vm = require('vm');
218 vm.runInNewContext('count += 1; name = "kitty"', sandbox);
219 console.log(util.inspect(sandbox));
221 // { animal: 'cat', count: 3, name: 'kitty' }
223 Note that running untrusted code is a tricky business requiring great care.
224 `vm.runInNewContext` is quite useful, but safely running untrusted code requires
227 ## vm.runInThisContext(code[, options])
229 `vm.runInThisContext()` compiles `code`, runs it and returns the result. Running
230 code does not have access to local scope, but does have access to the current
233 Example of using `vm.runInThisContext` and `eval` to run the same code:
235 var vm = require('vm');
236 var localVar = 'initial value';
238 var vmResult = vm.runInThisContext('localVar = "vm";');
239 console.log('vmResult: ', vmResult);
240 console.log('localVar: ', localVar);
242 var evalResult = eval('localVar = "eval";');
243 console.log('evalResult: ', evalResult);
244 console.log('localVar: ', localVar);
246 // vmResult: 'vm', localVar: 'initial value'
247 // evalResult: 'eval', localVar: 'eval'
249 `vm.runInThisContext` does not have access to the local scope, so `localVar` is
250 unchanged. `eval` does have access to the local scope, so `localVar` is changed.
252 In this way `vm.runInThisContext` is much like an [indirect `eval` call][1],
253 e.g. `(0,eval)('code')`. However, it also has the following additional options:
255 - `filename`: allows you to control the filename that shows up in any stack
257 - `displayErrors`: whether or not to print any errors to stderr, with the
258 line of code that caused them highlighted, before throwing an exception.
259 Will capture both syntax errors from compiling `code` and runtime errors
260 thrown by executing the compiled code. Defaults to `true`.
261 - `timeout`: a number of milliseconds to execute `code` before terminating
262 execution. If execution is terminated, an `Error` will be thrown.
264 [1]: http://es5.github.io/#x10.4.2