diff options
author | Franziska Hinkelmann <franziska.hinkelmann@gmail.com> | 2017-11-07 18:22:23 +0100 |
---|---|---|
committer | Franziska Hinkelmann <franzih@chromium.org> | 2017-11-09 21:29:55 +0100 |
commit | 5e1e460ac1d84b4b23a9c3a0280549b29af6ed1f (patch) | |
tree | 8adea3bfab6fbb0123aedd529f7db6ed8cb2492d /doc/api/vm.md | |
parent | f002c3d2edad51bfaaf825bc6c5a8ea78fe63d16 (diff) | |
download | android-node-v8-5e1e460ac1d84b4b23a9c3a0280549b29af6ed1f.tar.gz android-node-v8-5e1e460ac1d84b4b23a9c3a0280549b29af6ed1f.tar.bz2 android-node-v8-5e1e460ac1d84b4b23a9c3a0280549b29af6ed1f.zip |
doc: improve documentation for the vm module
Add an intro section and example for the vm module.
PR-URL: https://github.com/nodejs/node/pull/16867
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Gireesh Punathil <gpunathi@in.ibm.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Diffstat (limited to 'doc/api/vm.md')
-rw-r--r-- | doc/api/vm.md | 32 |
1 files changed, 28 insertions, 4 deletions
diff --git a/doc/api/vm.md b/doc/api/vm.md index 3b21ef0c4b..209302b450 100644 --- a/doc/api/vm.md +++ b/doc/api/vm.md @@ -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**. |