Merge remote-tracking branch 'upstream/v0.10' into v0.12
[platform/upstream/nodejs.git] / doc / api / vm.markdown
1 # Executing JavaScript
2
3     Stability: 3 - Stable
4
5 <!--name=vm-->
6
7 You can access this module with:
8
9     var vm = require('vm');
10
11 JavaScript code can be compiled and run immediately or compiled, saved, and run
12 later.
13
14 ## vm.runInThisContext(code, [options])
15
16 `vm.runInThisContext()` compiles `code`, runs it and returns the result. Running
17 code does not have access to local scope, but does have access to the current
18 `global` object.
19
20 Example of using `vm.runInThisContext` and `eval` to run the same code:
21
22     var localVar = 'initial value';
23
24     var vmResult = vm.runInThisContext('localVar = "vm";');
25     console.log('vmResult: ', vmResult);
26     console.log('localVar: ', localVar);
27
28     var evalResult = eval('localVar = "eval";');
29     console.log('evalResult: ', evalResult);
30     console.log('localVar: ', localVar);
31
32     // vmResult: 'vm', localVar: 'initial value'
33     // evalResult: 'eval', localVar: 'eval'
34
35 `vm.runInThisContext` does not have access to the local scope, so `localVar` is
36 unchanged. `eval` does have access to the local scope, so `localVar` is changed.
37
38 In this way `vm.runInThisContext` is much like an [indirect `eval` call][1],
39 e.g. `(0,eval)('code')`. However, it also has the following additional options:
40
41 - `filename`: allows you to control the filename that shows up in any stack
42   traces produced.
43 - `displayErrors`: whether or not to print any errors to stderr, with the
44   line of code that caused them highlighted, before throwing an exception.
45   Will capture both syntax errors from compiling `code` and runtime errors
46   thrown by executing the compiled code. Defaults to `true`.
47 - `timeout`: a number of milliseconds to execute `code` before terminating
48   execution. If execution is terminated, an `Error` will be thrown.
49
50 [1]: http://es5.github.io/#x10.4.2
51
52
53 ## vm.createContext([sandbox])
54
55 If given a `sandbox` object, will "contextify" that sandbox so that it can be
56 used in calls to `vm.runInContext` or `script.runInContext`. Inside scripts run
57 as such, `sandbox` will be the global object, retaining all its existing
58 properties but also having the built-in objects and functions any standard
59 [global object][2] has. Outside of scripts run by the vm module, `sandbox` will
60 be unchanged.
61
62 If not given a sandbox object, returns a new, empty contextified sandbox object
63 you can use.
64
65 This function is useful for creating a sandbox that can be used to run multiple
66 scripts, e.g. if you were emulating a web browser it could be used to create a
67 single sandbox representing a window's global object, then run all `<script>`
68 tags together inside that sandbox.
69
70 [2]: http://es5.github.io/#x15.1
71
72
73 ## vm.isContext(sandbox)
74
75 Returns whether or not a sandbox object has been contextified by calling
76 `vm.createContext` on it.
77
78
79 ## vm.runInContext(code, contextifiedSandbox, [options])
80
81 `vm.runInContext` compiles `code`, then runs it in `contextifiedSandbox` and
82 returns the result. Running code does not have access to local scope. The
83 `contextifiedSandbox` object must have been previously contextified via
84 `vm.createContext`; it will be used as the global object for `code`.
85
86 `vm.runInContext` takes the same options as `vm.runInThisContext`.
87
88 Example: compile and execute differnt scripts in a single existing context.
89
90     var util = require('util');
91     var vm = require('vm');
92
93     var sandbox = { globalVar: 1 };
94     vm.createContext(sandbox);
95
96     for (var i = 0; i < 10; ++i) {
97         vm.runInContext('globalVar *= 2;', sandbox);
98     }
99     console.log(util.inspect(sandbox));
100
101     // { globalVar: 1024 }
102
103 Note that running untrusted code is a tricky business requiring great care.
104 `vm.runInContext` is quite useful, but safely running untrusted code requires a
105 separate process.
106
107
108 ## vm.runInNewContext(code, [sandbox], [options])
109
110 `vm.runInNewContext` compiles `code`, contextifies `sandbox` if passed or
111 creates a new contextified sandbox if it's omitted, and then runs the code with
112 the sandbox as the global object and returns the result.
113
114 `vm.runInNewContext` takes the same options as `vm.runInThisContext`.
115
116 Example: compile and execute code that increments a global variable and sets a
117 new one. These globals are contained in the sandbox.
118
119     var util = require('util');
120     var vm = require('vm'),
121
122     var sandbox = {
123       animal: 'cat',
124       count: 2
125     };
126
127     vm.runInNewContext('count += 1; name = "kitty"', sandbox);
128     console.log(util.inspect(sandbox));
129
130     // { animal: 'cat', count: 3, name: 'kitty' }
131
132 Note that running untrusted code is a tricky business requiring great care.
133 `vm.runInNewContext` is quite useful, but safely running untrusted code requires
134 a separate process.
135
136
137 ## vm.runInDebugContext(code)
138
139 `vm.runInDebugContext` compiles and executes `code` inside the V8 debug context.
140 The primary use case is to get access to the V8 debug object:
141
142     var Debug = vm.runInDebugContext('Debug');
143     Debug.scripts().forEach(function(script) { console.log(script.name); });
144
145 Note that the debug context and object are intrinsically tied to V8's debugger
146 implementation and may change (or even get removed) without prior warning.
147
148 The debug object can also be exposed with the `--expose_debug_as=` switch.
149
150
151 ## Class: Script
152
153 A class for holding precompiled scripts, and running them in specific sandboxes.
154
155
156 ### new vm.Script(code, options)
157
158 Creating a new `Script` compiles `code` but does not run it. Instead, the
159 created `vm.Script` object represents this compiled code. This script can be run
160 later many times using methods below. The returned script is not bound to any
161 global object. It is bound before each run, just for that run.
162
163 The options when creating a script are:
164
165 - `filename`: allows you to control the filename that shows up in any stack
166   traces produced from this script.
167 - `displayErrors`: whether or not to print any errors to stderr, with the
168   line of code that caused them highlighted, before throwing an exception.
169   Applies only to syntax errors compiling the code; errors while running the
170   code are controlled by the options to the script's methods.
171
172
173 ### script.runInThisContext([options])
174
175 Similar to `vm.runInThisContext` but a method of a precompiled `Script` object.
176 `script.runInThisContext` runs `script`'s compiled code and returns the result.
177 Running code does not have access to local scope, but does have access to the
178 current `global` object.
179
180 Example of using `script.runInThisContext` to compile code once and run it
181 multiple times:
182
183     var vm = require('vm');
184
185     global.globalVar = 0;
186
187     var script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });
188
189     for (var i = 0; i < 1000; ++i) {
190       script.runInThisContext();
191     }
192
193     console.log(globalVar);
194
195     // 1000
196
197 The options for running a script are:
198
199 - `displayErrors`: whether or not to print any runtime errors to stderr, with
200   the line of code that caused them highlighted, before throwing an exception.
201   Applies only to runtime errors executing the code; it is impossible to create
202   a `Script` instance with syntax errors, as the constructor will throw.
203 - `timeout`: a number of milliseconds to execute the script before terminating
204   execution. If execution is terminated, an `Error` will be thrown.
205
206
207 ### script.runInContext(contextifiedSandbox, [options])
208
209 Similar to `vm.runInContext` but a method of a precompiled `Script` object.
210 `script.runInContext` runs `script`'s compiled code in `contextifiedSandbox`
211 and returns the result. Running code does not have access to local scope.
212
213 `script.runInContext` takes the same options as `script.runInThisContext`.
214
215 Example: compile code that increments a global variable and sets one, then
216 execute the code multiple times. These globals are contained in the sandbox.
217
218     var util = require('util');
219     var vm = require('vm');
220
221     var sandbox = {
222       animal: 'cat',
223       count: 2
224     };
225
226     var script = new vm.Script('count += 1; name = "kitty"');
227
228     for (var i = 0; i < 10; ++i) {
229       script.runInContext(sandbox);
230     }
231
232     console.log(util.inspect(sandbox));
233
234     // { animal: 'cat', count: 12, name: 'kitty' }
235
236 Note that running untrusted code is a tricky business requiring great care.
237 `script.runInContext` is quite useful, but safely running untrusted code
238 requires a separate process.
239
240
241 ### script.runInNewContext([sandbox], [options])
242
243 Similar to `vm.runInNewContext` but a method of a precompiled `Script` object.
244 `script.runInNewContext` contextifies `sandbox` if passed or creates a new
245 contextified sandbox if it's omitted, and then runs `script`'s compiled code
246 with the sandbox as the global object and returns the result. Running code does
247 not have access to local scope.
248
249 `script.runInNewContext` takes the same options as `script.runInThisContext`.
250
251 Example: compile code that sets a global variable, then execute the code
252 multiple times in different contexts. These globals are set on and contained in
253 the sandboxes.
254
255     var util = require('util');
256     var vm = require('vm');
257
258     var sandboxes = [{}, {}, {}];
259
260     var script = new vm.Script('globalVar = "set"');
261
262     sandboxes.forEach(function (sandbox) {
263       script.runInNewContext(sandbox);
264     });
265
266     console.log(util.inspect(sandboxes));
267
268     // [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]
269
270 Note that running untrusted code is a tricky business requiring great care.
271 `script.runInNewContext` is quite useful, but safely running untrusted code
272 requires a separate process.