doc: update links to use https where possible
[platform/upstream/nodejs.git] / doc / api / vm.markdown
1 # Executing JavaScript
2
3     Stability: 2 - Stable
4
5 <!--name=vm-->
6
7 You can access this module with:
8
9     const vm = require('vm');
10
11 JavaScript code can be compiled and run immediately or compiled, saved, and run
12 later.
13
14 ## Class: Script
15
16 A class for holding precompiled scripts, and running them in specific sandboxes.
17
18 ### new vm.Script(code, options)
19
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.
24
25 The options when creating a script are:
26
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.
39
40 ### script.runInContext(contextifiedSandbox[, options])
41
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.
45
46 `script.runInContext` takes the same options as `script.runInThisContext`.
47
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.
50
51     const util = require('util');
52     const vm = require('vm');
53
54     var sandbox = {
55       animal: 'cat',
56       count: 2
57     };
58
59     var context = new vm.createContext(sandbox);
60     var script = new vm.Script('count += 1; name = "kitty"');
61
62     for (var i = 0; i < 10; ++i) {
63       script.runInContext(context);
64     }
65
66     console.log(util.inspect(sandbox));
67
68     // { animal: 'cat', count: 12, name: 'kitty' }
69
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.
73
74 ### script.runInNewContext([sandbox][, options])
75
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.
81
82 `script.runInNewContext` takes the same options as `script.runInThisContext`.
83
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
86 the sandboxes.
87
88     const util = require('util');
89     const vm = require('vm');
90
91     const sandboxes = [{}, {}, {}];
92
93     const script = new vm.Script('globalVar = "set"');
94
95     sandboxes.forEach((sandbox) => {
96       script.runInNewContext(sandbox);
97     });
98
99     console.log(util.inspect(sandboxes));
100
101     // [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]
102
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.
106
107 ### script.runInThisContext([options])
108
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.
113
114 Example of using `script.runInThisContext` to compile code once and run it
115 multiple times:
116
117     const vm = require('vm');
118
119     global.globalVar = 0;
120
121     const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });
122
123     for (var i = 0; i < 1000; ++i) {
124       script.runInThisContext();
125     }
126
127     console.log(globalVar);
128
129     // 1000
130
131 The options for running a script are:
132
133 - `filename`: allows you to control the filename that shows up in any stack
134   traces produced.
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.
145
146 ## vm.createContext([sandbox])
147
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
153 be unchanged.
154
155 If not given a sandbox object, returns a new, empty contextified sandbox object
156 you can use.
157
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.
162
163 ## vm.isContext(sandbox)
164
165 Returns whether or not a sandbox object has been contextified by calling
166 `vm.createContext` on it.
167
168 ## vm.runInContext(code, contextifiedSandbox[, options])
169
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`.
174
175 `vm.runInContext` takes the same options as `vm.runInThisContext`.
176
177 Example: compile and execute different scripts in a single existing context.
178
179     const util = require('util');
180     const vm = require('vm');
181
182     const sandbox = { globalVar: 1 };
183     vm.createContext(sandbox);
184
185     for (var i = 0; i < 10; ++i) {
186         vm.runInContext('globalVar *= 2;', sandbox);
187     }
188     console.log(util.inspect(sandbox));
189
190     // { globalVar: 1024 }
191
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
194 separate process.
195
196 ## vm.runInDebugContext(code)
197
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:
200
201     const Debug = vm.runInDebugContext('Debug');
202     Debug.scripts().forEach(function(script) { console.log(script.name); });
203
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.
206
207 The debug object can also be exposed with the `--expose_debug_as=` switch.
208
209 ## vm.runInNewContext(code[, sandbox][, options])
210
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.
214
215 `vm.runInNewContext` takes the same options as `vm.runInThisContext`.
216
217 Example: compile and execute code that increments a global variable and sets a
218 new one. These globals are contained in the sandbox.
219
220     const util = require('util');
221     const vm = require('vm');
222
223     const sandbox = {
224       animal: 'cat',
225       count: 2
226     };
227
228     vm.runInNewContext('count += 1; name = "kitty"', sandbox);
229     console.log(util.inspect(sandbox));
230
231     // { animal: 'cat', count: 3, name: 'kitty' }
232
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
235 a separate process.
236
237 ## vm.runInThisContext(code[, options])
238
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
241 `global` object.
242
243 Example of using `vm.runInThisContext` and `eval` to run the same code:
244
245     const vm = require('vm');
246     var localVar = 'initial value';
247
248     const vmResult = vm.runInThisContext('localVar = "vm";');
249     console.log('vmResult: ', vmResult);
250     console.log('localVar: ', localVar);
251
252     const evalResult = eval('localVar = "eval";');
253     console.log('evalResult: ', evalResult);
254     console.log('localVar: ', localVar);
255
256     // vmResult: 'vm', localVar: 'initial value'
257     // evalResult: 'eval', localVar: 'eval'
258
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.
261
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:
264
265 - `filename`: allows you to control the filename that shows up in any stack
266   traces produced.
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.
277
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