Merge remote-tracking branch 'upstream/v0.10'
[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 ## Class: Script
138
139 A class for holding precompiled scripts, and running them in specific sandboxes.
140
141
142 ### new vm.Script(code, options)
143
144 Creating a new `Script` compiles `code` but does not run it. Instead, the
145 created `vm.Script` object represents this compiled code. This script can be run
146 later many times using methods below. The returned script is not bound to any
147 global object. It is bound before each run, just for that run.
148
149 The options when creating a script are:
150
151 - `filename`: allows you to control the filename that shows up in any stack
152   traces produced from this script.
153 - `displayErrors`: whether or not to print any errors to stderr, with the
154   line of code that caused them highlighted, before throwing an exception.
155   Applies only to syntax errors compiling the code; errors while running the
156   code are controlled by the options to the script's methods.
157
158
159 ### script.runInThisContext([options])
160
161 Similar to `vm.runInThisContext` but a method of a precompiled `Script` object.
162 `script.runInThisContext` runs `script`'s compiled code and returns the result.
163 Running code does not have access to local scope, but does have access to the
164 current `global` object.
165
166 Example of using `script.runInThisContext` to compile code once and run it
167 multiple times:
168
169     var vm = require('vm');
170
171     global.globalVar = 0;
172
173     var script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });
174
175     for (var i = 0; i < 1000; ++i) {
176       script.runInThisContext();
177     }
178
179     console.log(globalVar);
180
181     // 1000
182
183 The options for running a script are:
184
185 - `displayErrors`: whether or not to print any runtime errors to stderr, with
186   the line of code that caused them highlighted, before throwing an exception.
187   Applies only to runtime errors executing the code; it is impossible to create
188   a `Script` instance with syntax errors, as the constructor will throw.
189 - `timeout`: a number of milliseconds to execute the script before terminating
190   execution. If execution is terminated, an `Error` will be thrown.
191
192
193 ### script.runInContext(contextifiedSandbox, [options])
194
195 Similar to `vm.runInContext` but a method of a precompiled `Script` object.
196 `script.runInContext` runs `script`'s compiled code in `contextifiedSandbox`
197 and returns the result. Running code does not have access to local scope.
198
199 `script.runInContext` takes the same options as `script.runInThisContext`.
200
201 Example: compile code that increments a global variable and sets one, then
202 execute the code multiple times. These globals are contained in the sandbox.
203
204     var util = require('util');
205     var vm = require('vm');
206
207     var sandbox = {
208       animal: 'cat',
209       count: 2
210     };
211
212     var script = new vm.Script('count += 1; name = "kitty"');
213
214     for (var i = 0; i < 10; ++i) {
215       script.runInContext(sandbox);
216     }
217
218     console.log(util.inspect(sandbox));
219
220     // { animal: 'cat', count: 12, name: 'kitty' }
221
222 Note that running untrusted code is a tricky business requiring great care.
223 `script.runInContext` is quite useful, but safely running untrusted code
224 requires a separate process.
225
226
227 ### script.runInNewContext([sandbox], [options])
228
229 Similar to `vm.runInNewContext` but a method of a precompiled `Script` object.
230 `script.runInNewContext` contextifies `sandbox` if passed or creates a new
231 contextified sandbox if it's omitted, and then runs `script`'s compiled code
232 with the sandbox as the global object and returns the result. Running code does
233 not have access to local scope.
234
235 `script.runInNewContext` takes the same options as `script.runInThisContext`.
236
237 Example: compile code that sets a global variable, then execute the code
238 multiple times in different contexts. These globals are set on and contained in
239 the sandboxes.
240
241     var util = require('util');
242     var vm = require('vm');
243
244     var sandboxes = [{}, {}, {}];
245
246     var script = new vm.Script('globalVar = "set"');
247
248     sandboxes.forEach(function (sandbox) {
249       script.runInNewContext(sandbox);
250     });
251
252     console.log(util.inspect(sandboxes));
253
254     // [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]
255
256 Note that running untrusted code is a tricky business requiring great care.
257 `script.runInNewContext` is quite useful, but safely running untrusted code
258 requires a separate process.