doc: sort vm alphabetically
[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     var 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 - `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.
33
34 ### script.runInContext(contextifiedSandbox[, options])
35
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.
39
40 `script.runInContext` takes the same options as `script.runInThisContext`.
41
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.
44
45     var util = require('util');
46     var vm = require('vm');
47
48     var sandbox = {
49       animal: 'cat',
50       count: 2
51     };
52
53     var context = new vm.createContext(sandbox);
54     var script = new vm.Script('count += 1; name = "kitty"');
55
56     for (var i = 0; i < 10; ++i) {
57       script.runInContext(context);
58     }
59
60     console.log(util.inspect(sandbox));
61
62     // { animal: 'cat', count: 12, name: 'kitty' }
63
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.
67
68 ### script.runInNewContext([sandbox][, options])
69
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.
75
76 `script.runInNewContext` takes the same options as `script.runInThisContext`.
77
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
80 the sandboxes.
81
82     var util = require('util');
83     var vm = require('vm');
84
85     var sandboxes = [{}, {}, {}];
86
87     var script = new vm.Script('globalVar = "set"');
88
89     sandboxes.forEach(function (sandbox) {
90       script.runInNewContext(sandbox);
91     });
92
93     console.log(util.inspect(sandboxes));
94
95     // [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]
96
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.
100
101 ### script.runInThisContext([options])
102
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.
107
108 Example of using `script.runInThisContext` to compile code once and run it
109 multiple times:
110
111     var vm = require('vm');
112
113     global.globalVar = 0;
114
115     var script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });
116
117     for (var i = 0; i < 1000; ++i) {
118       script.runInThisContext();
119     }
120
121     console.log(globalVar);
122
123     // 1000
124
125 The options for running a script are:
126
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.
133
134 ## vm.createContext([sandbox])
135
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
141 be unchanged.
142
143 If not given a sandbox object, returns a new, empty contextified sandbox object
144 you can use.
145
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.
150
151 [2]: http://es5.github.io/#x15.1
152
153 ## vm.isContext(sandbox)
154
155 Returns whether or not a sandbox object has been contextified by calling
156 `vm.createContext` on it.
157
158 ## vm.runInContext(code, contextifiedSandbox[, options])
159
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`.
164
165 `vm.runInContext` takes the same options as `vm.runInThisContext`.
166
167 Example: compile and execute different scripts in a single existing context.
168
169     var util = require('util');
170     var vm = require('vm');
171
172     var sandbox = { globalVar: 1 };
173     vm.createContext(sandbox);
174
175     for (var i = 0; i < 10; ++i) {
176         vm.runInContext('globalVar *= 2;', sandbox);
177     }
178     console.log(util.inspect(sandbox));
179
180     // { globalVar: 1024 }
181
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
184 separate process.
185
186 ## vm.runInDebugContext(code)
187
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:
190
191     var Debug = vm.runInDebugContext('Debug');
192     Debug.scripts().forEach(function(script) { console.log(script.name); });
193
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.
196
197 The debug object can also be exposed with the `--expose_debug_as=` switch.
198
199 ## vm.runInNewContext(code[, sandbox][, options])
200
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.
204
205 `vm.runInNewContext` takes the same options as `vm.runInThisContext`.
206
207 Example: compile and execute code that increments a global variable and sets a
208 new one. These globals are contained in the sandbox.
209
210     var util = require('util');
211     var vm = require('vm');
212
213     var sandbox = {
214       animal: 'cat',
215       count: 2
216     };
217
218     vm.runInNewContext('count += 1; name = "kitty"', sandbox);
219     console.log(util.inspect(sandbox));
220
221     // { animal: 'cat', count: 3, name: 'kitty' }
222
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
225 a separate process.
226
227 ## vm.runInThisContext(code[, options])
228
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
231 `global` object.
232
233 Example of using `vm.runInThisContext` and `eval` to run the same code:
234
235     var vm = require('vm');
236     var localVar = 'initial value';
237
238     var vmResult = vm.runInThisContext('localVar = "vm";');
239     console.log('vmResult: ', vmResult);
240     console.log('localVar: ', localVar);
241
242     var evalResult = eval('localVar = "eval";');
243     console.log('evalResult: ', evalResult);
244     console.log('localVar: ', localVar);
245
246     // vmResult: 'vm', localVar: 'initial value'
247     // evalResult: 'eval', localVar: 'eval'
248
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.
251
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:
254
255 - `filename`: allows you to control the filename that shows up in any stack
256   traces produced.
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.
263
264 [1]: http://es5.github.io/#x10.4.2