Namespace node.vm
You can access this module with:
var vm = require('vm');
JavaScript code can be compiled and run immediately or compiled, saved, and run later.
- Defined in: node.vm.js
Method Summary
| Method Attributes | Method Name and Description |
|---|---|
| static |
node.vm.createContext()
|
| static |
node.vm.createScript(code, ctx, name)
createScript compiles code as if it were loaded from filename,
but does not run it. |
| static |
node.vm.runInContext()
|
| static |
node.vm.runInNewContext()
Similar to
vm.runInNewContext a method of a precompiled Script object. |
| static |
node.vm.runInThisContext()
Similar to
vm.runInThisContext but a method of a precompiled Script object. |
Method Detail
-
static node.vm.createContext()
-
static node.vm.createScript(code, ctx, name)
createScriptcompilescodeas if it were loaded fromfilename, but does not run it. Instead, it returns avm.Scriptobject representing this compiled code. This script can be run later many times using methods below. The returned script is not bound to any global object. It is bound before each run, just for that run.filenameis optional. In case of syntax error incode,createScriptprints the syntax error to stderr and throws an exception.- Parameters:
- {string} code
- {string} ctx
- {string} name
-
static node.vm.runInContext()
-
static node.vm.runInNewContext()Similar to
vm.runInNewContexta method of a precompiledScriptobject.script.runInNewContextruns the code ofscriptwithsandboxas the global object and returns the result. Running code does not have access to local scope.sandboxis optional. Example: compile code that increments a global variable and sets one, then execute this code multiple times. These globals are contained in the sandbox.var util = require('util'), vm = require('vm'), sandbox = { animal: 'cat', count: 2 }; var script = vm.createScript('count += 1; name = "kitty"', 'myfile.vm'); for (var i = 0; i < 10 ; i += 1) { script.runInNewContext(sandbox); } console.log(util.inspect(sandbox)); // { animal: 'cat', count: 12, name: 'kitty' }Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage,script.runInNewContextis quite useful, but safely running untrusted code requires a separate process. -
static node.vm.runInThisContext()Similar to
vm.runInThisContextbut a method of a precompiledScriptobject.script.runInThisContextruns the code ofscriptand returns the result. Running code does not have access to local scope, but does have access to theglobalobject (v8: in actual context). Example of usingscript.runInThisContextto compile code once and run it multiple times:var vm = require('vm'); globalVar = 0; var script = vm.createScript('globalVar += 1', 'myfile.vm'); for (var i = 0; i < 1000 ; i += 1) { script.runInThisContext(); } console.log(globalVar); // 1000