7 You can access this module with:
9 const 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 - `lineOffset`: allows you to add an offset to the line number that is
30 displayed in stack traces
31 - `columnOffset`: allows you to add an offset to the column number that is
32 displayed in stack traces
33 - `displayErrors`: whether or not to print any errors to stderr, with the
34 line of code that caused them highlighted, before throwing an exception.
35 Applies only to syntax errors compiling the code; errors while running the
36 code are controlled by the options to the script's methods.
37 - `timeout`: a number of milliseconds to execute `code` before terminating
38 execution. If execution is terminated, an [`Error`][] will be thrown.
40 ### script.runInContext(contextifiedSandbox[, options])
42 Similar to `vm.runInContext` but a method of a precompiled `Script` object.
43 `script.runInContext` runs `script`'s compiled code in `contextifiedSandbox`
44 and returns the result. Running code does not have access to local scope.
46 `script.runInContext` takes the same options as `script.runInThisContext`.
48 Example: compile code that increments a global variable and sets one, then
49 execute the code multiple times. These globals are contained in the sandbox.
51 const util = require('util');
52 const vm = require('vm');
59 var context = new vm.createContext(sandbox);
60 var script = new vm.Script('count += 1; name = "kitty"');
62 for (var i = 0; i < 10; ++i) {
63 script.runInContext(context);
66 console.log(util.inspect(sandbox));
68 // { animal: 'cat', count: 12, name: 'kitty' }
70 Note that running untrusted code is a tricky business requiring great care.
71 `script.runInContext` is quite useful, but safely running untrusted code
72 requires a separate process.
74 ### script.runInNewContext([sandbox][, options])
76 Similar to `vm.runInNewContext` but a method of a precompiled `Script` object.
77 `script.runInNewContext` contextifies `sandbox` if passed or creates a new
78 contextified sandbox if it's omitted, and then runs `script`'s compiled code
79 with the sandbox as the global object and returns the result. Running code does
80 not have access to local scope.
82 `script.runInNewContext` takes the same options as `script.runInThisContext`.
84 Example: compile code that sets a global variable, then execute the code
85 multiple times in different contexts. These globals are set on and contained in
88 const util = require('util');
89 const vm = require('vm');
91 const sandboxes = [{}, {}, {}];
93 const script = new vm.Script('globalVar = "set"');
95 sandboxes.forEach((sandbox) => {
96 script.runInNewContext(sandbox);
99 console.log(util.inspect(sandboxes));
101 // [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]
103 Note that running untrusted code is a tricky business requiring great care.
104 `script.runInNewContext` is quite useful, but safely running untrusted code
105 requires a separate process.
107 ### script.runInThisContext([options])
109 Similar to `vm.runInThisContext` but a method of a precompiled `Script` object.
110 `script.runInThisContext` runs `script`'s compiled code and returns the result.
111 Running code does not have access to local scope, but does have access to the
112 current `global` object.
114 Example of using `script.runInThisContext` to compile code once and run it
117 const vm = require('vm');
119 global.globalVar = 0;
121 const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });
123 for (var i = 0; i < 1000; ++i) {
124 script.runInThisContext();
127 console.log(globalVar);
131 The options for running a script are:
133 - `filename`: allows you to control the filename that shows up in any stack
135 - `lineOffset`: allows you to add an offset to the line number that is
136 displayed in stack traces
137 - `columnOffset`: allows you to add an offset to the column number that is
138 displayed in stack traces
139 - `displayErrors`: whether or not to print any errors to stderr, with the
140 line of code that caused them highlighted, before throwing an exception.
141 Applies only to runtime errors executing the code; it is impossible to create
142 a `Script` instance with syntax errors, as the constructor will throw.
143 - `timeout`: a number of milliseconds to execute the script before terminating
144 execution. If execution is terminated, an [`Error`][] will be thrown.
146 ## vm.createContext([sandbox])
148 If given a `sandbox` object, will "contextify" that sandbox so that it can be
149 used in calls to `vm.runInContext` or `script.runInContext`. Inside scripts run
150 as such, `sandbox` will be the global object, retaining all its existing
151 properties but also having the built-in objects and functions any standard
152 [global object][] has. Outside of scripts run by the vm module, `sandbox` will
155 If not given a sandbox object, returns a new, empty contextified sandbox object
158 This function is useful for creating a sandbox that can be used to run multiple
159 scripts, e.g. if you were emulating a web browser it could be used to create a
160 single sandbox representing a window's global object, then run all `<script>`
161 tags together inside that sandbox.
163 ## vm.isContext(sandbox)
165 Returns whether or not a sandbox object has been contextified by calling
166 `vm.createContext` on it.
168 ## vm.runInContext(code, contextifiedSandbox[, options])
170 `vm.runInContext` compiles `code`, then runs it in `contextifiedSandbox` and
171 returns the result. Running code does not have access to local scope. The
172 `contextifiedSandbox` object must have been previously contextified via
173 `vm.createContext`; it will be used as the global object for `code`.
175 `vm.runInContext` takes the same options as `vm.runInThisContext`.
177 Example: compile and execute different scripts in a single existing context.
179 const util = require('util');
180 const vm = require('vm');
182 const sandbox = { globalVar: 1 };
183 vm.createContext(sandbox);
185 for (var i = 0; i < 10; ++i) {
186 vm.runInContext('globalVar *= 2;', sandbox);
188 console.log(util.inspect(sandbox));
190 // { globalVar: 1024 }
192 Note that running untrusted code is a tricky business requiring great care.
193 `vm.runInContext` is quite useful, but safely running untrusted code requires a
196 ## vm.runInDebugContext(code)
198 `vm.runInDebugContext` compiles and executes `code` inside the V8 debug context.
199 The primary use case is to get access to the V8 debug object:
201 const Debug = vm.runInDebugContext('Debug');
202 Debug.scripts().forEach(function(script) { console.log(script.name); });
204 Note that the debug context and object are intrinsically tied to V8's debugger
205 implementation and may change (or even get removed) without prior warning.
207 The debug object can also be exposed with the `--expose_debug_as=` switch.
209 ## vm.runInNewContext(code[, sandbox][, options])
211 `vm.runInNewContext` compiles `code`, contextifies `sandbox` if passed or
212 creates a new contextified sandbox if it's omitted, and then runs the code with
213 the sandbox as the global object and returns the result.
215 `vm.runInNewContext` takes the same options as `vm.runInThisContext`.
217 Example: compile and execute code that increments a global variable and sets a
218 new one. These globals are contained in the sandbox.
220 const util = require('util');
221 const vm = require('vm');
228 vm.runInNewContext('count += 1; name = "kitty"', sandbox);
229 console.log(util.inspect(sandbox));
231 // { animal: 'cat', count: 3, name: 'kitty' }
233 Note that running untrusted code is a tricky business requiring great care.
234 `vm.runInNewContext` is quite useful, but safely running untrusted code requires
237 ## vm.runInThisContext(code[, options])
239 `vm.runInThisContext()` compiles `code`, runs it and returns the result. Running
240 code does not have access to local scope, but does have access to the current
243 Example of using `vm.runInThisContext` and `eval` to run the same code:
245 const vm = require('vm');
246 var localVar = 'initial value';
248 const vmResult = vm.runInThisContext('localVar = "vm";');
249 console.log('vmResult: ', vmResult);
250 console.log('localVar: ', localVar);
252 const evalResult = eval('localVar = "eval";');
253 console.log('evalResult: ', evalResult);
254 console.log('localVar: ', localVar);
256 // vmResult: 'vm', localVar: 'initial value'
257 // evalResult: 'eval', localVar: 'eval'
259 `vm.runInThisContext` does not have access to the local scope, so `localVar` is
260 unchanged. `eval` does have access to the local scope, so `localVar` is changed.
262 In this way `vm.runInThisContext` is much like an [indirect `eval` call][],
263 e.g. `(0,eval)('code')`. However, it also has the following additional options:
265 - `filename`: allows you to control the filename that shows up in any stack
267 - `lineOffset`: allows you to add an offset to the line number that is
268 displayed in stack traces
269 - `columnOffset`: allows you to add an offset to the column number that is
270 displayed in stack traces
271 - `displayErrors`: whether or not to print any errors to stderr, with the
272 line of code that caused them highlighted, before throwing an exception.
273 Will capture both syntax errors from compiling `code` and runtime errors
274 thrown by executing the compiled code. Defaults to `true`.
275 - `timeout`: a number of milliseconds to execute `code` before terminating
276 execution. If execution is terminated, an [`Error`][] will be thrown.
278 [indirect `eval` call]: https://es5.github.io/#x10.4.2
279 [global object]: https://es5.github.io/#x15.1
280 [`Error`]: errors.html#errors_class_error