|
7 | 7 | <!--name=vm-->
|
8 | 8 |
|
9 | 9 | The `vm` module provides APIs for compiling and running code within V8 Virtual
|
10 |
| -Machine contexts. It can be accessed using: |
| 10 | +Machine contexts. |
| 11 | + |
| 12 | +JavaScript code can be compiled and run immediately or |
| 13 | +compiled, saved, and run later. |
| 14 | + |
| 15 | +A common use case is to run the code in a sandboxed environment. |
| 16 | +The sandboxed code uses a different V8 Context, meaning that |
| 17 | +it has a different global object than the rest of the code. |
| 18 | + |
| 19 | +One can provide the context by ["contextifying"][contextified] a sandbox |
| 20 | +object. The sandboxed code treats any property on the sandbox like a |
| 21 | +global variable. Any changes on global variables caused by the sandboxed |
| 22 | +code are reflected in the sandbox object. |
11 | 23 |
|
12 | 24 | ```js
|
13 | 25 | const vm = require('vm');
|
14 |
| -``` |
15 | 26 |
|
16 |
| -JavaScript code can be compiled and run immediately or compiled, saved, and run |
17 |
| -later. |
| 27 | +const x = 1; |
| 28 | + |
| 29 | +const sandbox = { x: 2 }; |
| 30 | +vm.createContext(sandbox); // Contextify the sandbox. |
| 31 | + |
| 32 | +const code = 'x += 40; var y = 17;'; |
| 33 | +// x and y are global variables in the sandboxed environment. |
| 34 | +// Initially, x has the value 2 because that is the value of sandbox.x. |
| 35 | +vm.runInContext(code, sandbox); |
| 36 | + |
| 37 | +console.log(sandbox.x); // 42 |
| 38 | +console.log(sandbox.y); // 17 |
| 39 | + |
| 40 | +console.log(x); // 1; y is not defined. |
| 41 | +``` |
18 | 42 |
|
19 | 43 | *Note*: The vm module is not a security mechanism.
|
20 | 44 | **Do not use it to run untrusted code**.
|
|
0 commit comments