doc: Fix link to open issues on GitHub.
[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 [the open issues on
17 GitHub](https://github.com/joyent/node/search?q=vm+state%3Aopen&type=Issues).
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])
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
89 Example: compile and execute code that increments a global variable and sets a new one.
90 These globals are contained in the sandbox.
91
92     var util = require('util'),
93         vm = require('vm'),
94         sandbox = {
95           animal: 'cat',
96           count: 2
97         };
98
99     vm.runInNewContext('count += 1; name = "kitty"', sandbox, 'myfile.vm');
100     console.log(util.inspect(sandbox));
101
102     // { animal: 'cat', count: 3, name: 'kitty' }
103
104 Note that running untrusted code is a tricky business requiring great care.  To prevent accidental
105 global variable leakage, `vm.runInNewContext` is quite useful, but safely running untrusted code
106 requires a separate process.
107
108 In case of syntax error in `code`, `vm.runInNewContext` emits the syntax error to stderr
109 and throws an exception.
110
111 ## vm.runInContext(code, context, [filename])
112
113 `vm.runInContext` compiles `code`, then runs it in `context` and returns the
114 result. A (V8) context comprises a global object, together with a set of
115 built-in objects and functions. Running code does not have access to local scope
116 and the global object held within `context` will be used as the global object
117 for `code`.
118 `filename` is optional, it's used only in stack traces.
119
120 Example: compile and execute code in a existing context.
121
122     var util = require('util'),
123         vm = require('vm'),
124         initSandbox = {
125           animal: 'cat',
126           count: 2
127         },
128         context = vm.createContext(initSandbox);
129
130     vm.runInContext('count += 1; name = "CATT"', context, 'myfile.vm');
131     console.log(util.inspect(context));
132
133     // { animal: 'cat', count: 3, name: 'CATT' }
134
135 Note that `createContext` will perform a shallow clone of the supplied sandbox object in order to
136 initialize the global object of the freshly constructed context.
137
138 Note that running untrusted code is a tricky business requiring great care.  To prevent accidental
139 global variable leakage, `vm.runInContext` is quite useful, but safely running untrusted code
140 requires a separate process.
141
142 In case of syntax error in `code`, `vm.runInContext` emits the syntax error to stderr
143 and throws an exception.
144
145 ## vm.createContext([initSandbox])
146
147 `vm.createContext` creates a new context which is suitable for use as the 2nd argument of a subsequent
148 call to `vm.runInContext`. A (V8) context comprises a global object together with a set of
149 build-in objects and functions. The optional argument `initSandbox` will be shallow-copied
150 to seed the initial contents of the global object used by the context.
151
152 ## vm.createScript(code, [filename])
153
154 `createScript` compiles `code` but does not run it. Instead, it returns a
155 `vm.Script` object representing this compiled code. This script can be run
156 later many times using methods below. The returned script is not bound to any
157 global object. It is bound before each run, just for that run. `filename` is
158 optional, it's only used in stack traces.
159
160 In case of syntax error in `code`, `createScript` prints the syntax error to stderr
161 and throws an exception.
162
163
164 ## Class: Script
165
166 A class for running scripts.  Returned by vm.createScript.
167
168 ### script.runInThisContext()
169
170 Similar to `vm.runInThisContext` but a method of a precompiled `Script` object.
171 `script.runInThisContext` runs the code of `script` and returns the result.
172 Running code does not have access to local scope, but does have access to the `global` object
173 (v8: in actual context).
174
175 Example of using `script.runInThisContext` to compile code once and run it multiple times:
176
177     var vm = require('vm');
178
179     globalVar = 0;
180
181     var script = vm.createScript('globalVar += 1', 'myfile.vm');
182
183     for (var i = 0; i < 1000 ; i += 1) {
184       script.runInThisContext();
185     }
186
187     console.log(globalVar);
188
189     // 1000
190
191
192 ### script.runInNewContext([sandbox])
193
194 Similar to `vm.runInNewContext` a method of a precompiled `Script` object.
195 `script.runInNewContext` runs the code of `script` with `sandbox` as the global object and returns the result.
196 Running code does not have access to local scope. `sandbox` is optional.
197
198 Example: compile code that increments a global variable and sets one, then execute this code multiple times.
199 These globals are contained in the sandbox.
200
201     var util = require('util'),
202         vm = require('vm'),
203         sandbox = {
204           animal: 'cat',
205           count: 2
206         };
207
208     var script = vm.createScript('count += 1; name = "kitty"', 'myfile.vm');
209
210     for (var i = 0; i < 10 ; i += 1) {
211       script.runInNewContext(sandbox);
212     }
213
214     console.log(util.inspect(sandbox));
215
216     // { animal: 'cat', count: 12, name: 'kitty' }
217
218 Note that running untrusted code is a tricky business requiring great care.  To prevent accidental
219 global variable leakage, `script.runInNewContext` is quite useful, but safely running untrusted code
220 requires a separate process.