vm: add support for timeout argument
[platform/upstream/nodejs.git] / doc / api / vm.markdown
1 # Executing JavaScript
2
3     Stability: 2 - Unstable. See Caveats, below.
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 later.
12
13 ## Caveats
14
15 The `vm` module has many known issues and edge cases. If you run into
16 issues or unexpected behavior, please consult
17 [the open issues on GitHub](https://github.com/joyent/node/issues/search?q=vm).
18 Some of the biggest problems are described below.
19
20 ### Sandboxes
21
22 The `sandbox` argument to `vm.runInNewContext` and `vm.createContext`,
23 along with the `initSandbox` argument to `vm.createContext`, do not
24 behave as one might normally expect and their behavior varies
25 between different versions of Node.
26
27 The key issue to be aware of is that V8 provides no way to directly
28 control the global object used within a context. As a result, while
29 properties of your `sandbox` object will be available in the context,
30 any properties from the `prototype`s of the `sandbox` may not be
31 available. Furthermore, the `this` expression within the global scope
32 of the context evaluates to the empty object (`{}`) instead of to
33 your sandbox.
34
35 Your sandbox's properties are also not shared directly with the script.
36 Instead, the properties of the sandbox are copied into the context at
37 the beginning of execution, and then after execution, the properties
38 are copied back out in an attempt to propagate any changes.
39
40 ### Globals
41
42 Properties of the global object, like `Array` and `String`, have
43 different values inside of a context. This means that common
44 expressions like `[] instanceof Array` or
45 `Object.getPrototypeOf([]) === Array.prototype` may not produce
46 expected results when used inside of scripts evaluated via the `vm` module.
47
48 Some of these problems have known workarounds listed in the issues for
49 `vm` on GitHub. for example, `Array.isArray` works around
50 the example problem with `Array`.
51
52 ## vm.runInThisContext(code, [filename])
53
54 `vm.runInThisContext()` compiles `code`, runs it and returns the result. Running
55 code does not have access to local scope. `filename` is optional, it's used only
56 in stack traces.
57
58 Example of using `vm.runInThisContext` and `eval` to run the same code:
59
60     var localVar = 123,
61         usingscript, evaled,
62         vm = require('vm');
63
64     usingscript = vm.runInThisContext('localVar = 1;',
65       'myfile.vm');
66     console.log('localVar: ' + localVar + ', usingscript: ' +
67       usingscript);
68     evaled = eval('localVar = 1;');
69     console.log('localVar: ' + localVar + ', evaled: ' +
70       evaled);
71
72     // localVar: 123, usingscript: 1
73     // localVar: 1, evaled: 1
74
75 `vm.runInThisContext` does not have access to the local scope, so `localVar` is unchanged.
76 `eval` does have access to the local scope, so `localVar` is changed.
77
78 In case of syntax error in `code`, `vm.runInThisContext` emits the syntax error to stderr
79 and throws an exception.
80
81
82 ## vm.runInNewContext(code, [sandbox], [filename], [timeout])
83
84 `vm.runInNewContext` compiles `code`, then runs it in `sandbox` and returns the
85 result. Running code does not have access to local scope. The object `sandbox`
86 will be used as the global object for `code`.
87 `sandbox` and `filename` are optional, `filename` is only used in stack traces.
88 `timeout` specifies an optional number of milliseconds to execute `code` before
89 terminating execution. If execution is terminated, `null` will be thrown.
90
91 Example: compile and execute code that increments a global variable and sets a new one.
92 These globals are contained in the sandbox.
93
94     var util = require('util'),
95         vm = require('vm'),
96         sandbox = {
97           animal: 'cat',
98           count: 2
99         };
100
101     vm.runInNewContext('count += 1; name = "kitty"', sandbox, 'myfile.vm');
102     console.log(util.inspect(sandbox));
103
104     // { animal: 'cat', count: 3, name: 'kitty' }
105
106 Note that running untrusted code is a tricky business requiring great care.  To prevent accidental
107 global variable leakage, `vm.runInNewContext` is quite useful, but safely running untrusted code
108 requires a separate process.
109
110 In case of syntax error in `code`, `vm.runInNewContext` emits the syntax error to stderr
111 and throws an exception.
112
113 ## vm.runInContext(code, context, [filename], [timeout])
114
115 `vm.runInContext` compiles `code`, then runs it in `context` and returns the
116 result. A (V8) context comprises a global object, together with a set of
117 built-in objects and functions. Running code does not have access to local scope
118 and the global object held within `context` will be used as the global object
119 for `code`.
120 `filename` is optional, it's used only in stack traces.
121 `timeout` specifies an optional number of milliseconds to execute `code` before
122 terminating execution. If execution is terminated, `null` will be thrown.
123
124 Example: compile and execute code in a existing context.
125
126     var util = require('util'),
127         vm = require('vm'),
128         initSandbox = {
129           animal: 'cat',
130           count: 2
131         },
132         context = vm.createContext(initSandbox);
133
134     vm.runInContext('count += 1; name = "CATT"', context, 'myfile.vm');
135     console.log(util.inspect(context));
136
137     // { animal: 'cat', count: 3, name: 'CATT' }
138
139 Note that `createContext` will perform a shallow clone of the supplied sandbox object in order to
140 initialize the global object of the freshly constructed context.
141
142 Note that running untrusted code is a tricky business requiring great care.  To prevent accidental
143 global variable leakage, `vm.runInContext` is quite useful, but safely running untrusted code
144 requires a separate process.
145
146 In case of syntax error in `code`, `vm.runInContext` emits the syntax error to stderr
147 and throws an exception.
148
149 ## vm.createContext([initSandbox])
150
151 `vm.createContext` creates a new context which is suitable for use as the 2nd argument of a subsequent
152 call to `vm.runInContext`. A (V8) context comprises a global object together with a set of
153 build-in objects and functions. The optional argument `initSandbox` will be shallow-copied
154 to seed the initial contents of the global object used by the context.
155
156 ## vm.createScript(code, [filename])
157
158 `createScript` compiles `code` but does not run it. Instead, it returns a
159 `vm.Script` object representing 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. `filename` is
162 optional, it's only used in stack traces.
163
164 In case of syntax error in `code`, `createScript` prints the syntax error to stderr
165 and throws an exception.
166
167
168 ## Class: Script
169
170 A class for running scripts.  Returned by vm.createScript.
171
172 ### script.runInThisContext([timeout])
173
174 Similar to `vm.runInThisContext` but a method of a precompiled `Script` object.
175 `script.runInThisContext` runs the code of `script` and returns the result.
176 Running code does not have access to local scope, but does have access to the `global` object
177 (v8: in actual context).
178 `timeout` specifies an optional number of milliseconds to execute `code` before
179 terminating execution. If execution is terminated, `null` will be thrown.
180
181 Example of using `script.runInThisContext` to compile code once and run it multiple times:
182
183     var vm = require('vm');
184
185     globalVar = 0;
186
187     var script = vm.createScript('globalVar += 1', 'myfile.vm');
188
189     for (var i = 0; i < 1000 ; i += 1) {
190       script.runInThisContext();
191     }
192
193     console.log(globalVar);
194
195     // 1000
196
197
198 ### script.runInNewContext([sandbox], [timeout])
199
200 Similar to `vm.runInNewContext` a method of a precompiled `Script` object.
201 `script.runInNewContext` runs the code of `script` with `sandbox` as the global object and returns the result.
202 Running code does not have access to local scope. `sandbox` is optional.
203 `timeout` specifies an optional number of milliseconds to execute `code` before
204 terminating execution. If execution is terminated, `null` will be thrown.
205
206 Example: compile code that increments a global variable and sets one, then execute this code multiple times.
207 These globals are contained in the sandbox.
208
209     var util = require('util'),
210         vm = require('vm'),
211         sandbox = {
212           animal: 'cat',
213           count: 2
214         };
215
216     var script = vm.createScript('count += 1; name = "kitty"', 'myfile.vm');
217
218     for (var i = 0; i < 10 ; i += 1) {
219       script.runInNewContext(sandbox);
220     }
221
222     console.log(util.inspect(sandbox));
223
224     // { animal: 'cat', count: 12, name: 'kitty' }
225
226 Note that running untrusted code is a tricky business requiring great care.  To prevent accidental
227 global variable leakage, `script.runInNewContext` is quite useful, but safely running untrusted code
228 requires a separate process.