Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

doc: improve documentation for the vm module #16867

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 28 additions & 4 deletions doc/api/vm.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,38 @@
<!--name=vm-->

The `vm` module provides APIs for compiling and running code within V8 Virtual
Machine contexts. It can be accessed using:
Machine contexts.

JavaScript code can be compiled and run immediately or
compiled, saved, and run later.

A common use case is to run the code in a sandboxed environment.
The sandboxed code uses a different V8 Context, meaning that
it has a different global object than the rest of the code.

One can provide the context by ["contextifying"][contextified] a sandbox
object. The sandboxed code treats any property on the sandbox like a
global variable. Any changes on global variables caused by the sandboxed
code are reflected in the sandbox object.

```js
const vm = require('vm');
```

JavaScript code can be compiled and run immediately or compiled, saved, and run
later.
const x = 1;

const sandbox = { x: 2 };
vm.createContext(sandbox); // Contextify the sandbox.

const code = 'x += 40; var y = 17;';
// x and y are global variables in the sandboxed environment.
// Initially, x has the value 2 because that is the value of sandbox.x.
vm.runInContext(code, sandbox);

console.log(sandbox.x); // 42
console.log(sandbox.y); // 17

console.log(x); // 1; y is not defined.
```

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