Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit d721c0b

Browse filesBrowse 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 585f869 commit d721c0b
Copy full SHA for d721c0b

File tree

Expand file treeCollapse file tree

1 file changed

+28
-4
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

1 file changed

+28
-4
lines changed
Open diff view settings
Collapse file

‎doc/api/vm.md‎

Copy file name to clipboardExpand all lines: doc/api/vm.md
+28-4Lines changed: 28 additions & 4 deletions
  • Display the source diff
  • Display the rich diff
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 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.