Skip to content

Commit 1fa1ad2

Browse files
fhinkelMylesBorins
authored andcommitted
doc: improve documentation for the vm module
Add an intro section and example for the vm module. PR-URL: #16867 Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: Gireesh Punathil <gpunathi@in.ibm.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
1 parent 5e4de71 commit 1fa1ad2

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

doc/api/vm.md

+28-4
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,38 @@
77
<!--name=vm-->
88

99
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.
1123

1224
```js
1325
const vm = require('vm');
14-
```
1526

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+
```
1842

1943
*Note*: The vm module is not a security mechanism.
2044
**Do not use it to run untrusted code**.

0 commit comments

Comments
 (0)