Updated: May 6, 2015 10:21:50 Contributor: junjie I want to comment
This article describes the VM module Detailed NodeJs, this paper explains what a VM? Content runInThisContext VM module, runInThisContext method, can refer to a friend
What is VM?
VM module is NodeJS inside the core module, supporting and operating mechanism NodeJS methods require, and sometimes we may have to use VM template to do something special.
By VM, JS can be compiled immediately after the implementation of the compiler or preserved performed later (Compiled and JavaScript code CAN BE RUN or Immediately is Compiled, saved, and RUN later.)
VM module contains three common methods for creating independent sandbox running system, the following three methods
vm.runInThisContext (code, filename);
This method is used to create a separate space sandbox to run the code in the code can access external global object, but can not access other variables
And internal global code share with the outside
Copy the code code is as follows:
the require VM = var ( "VM");
var P =. 5;
global.p = 11;
vm.runInThisContext ( "the console.log ( 'OK', P)"); // display 11 under the Global
vm.runInThisContext ( "console.log (global)"); // show Global
the console.log (P); // display. 5
vm.runInContext (code, Sandbox);
This method is used to create a stand-alone sandbox running space, sandBox will serve as global variables within the incoming code, but the global variable does not exist
sandBox requirement is sandBox vm.createContext () method creates
Copy the code code is as follows:
var vm = require("vm");
var util = require("util");
var window = {
p: 2,
vm: vm,
console: console,
require: require
};
var p = 5;
global.p = 11;
vm.createContext(window);
vm.runInContext('p = 3;console.log(typeof global);', window); // global是undefined
console.log(window.p);// 被改变为3
console.log(util.inspect(window));
vm.runInNewContext(code, sandbox, opt);
This method should runInContext the same, but fewer steps to create sandBox
Compare
The situation is more complex
if there runInContext execution runInThisContext be like, runInThisContext access to the global target who is?
The following code will be how to implement?
Copy the code code is as follows:
var vm = require("vm");
var util = require("util");
var window = {
p: 2,
vm: vm,
console: console,
require: require
};
window.global = window;
var p = 5;
global.p = 11;
vm.runInNewContext('p = 3;console.log(typeof global);require(\'vm\').runInThisContext("console.log(p)");', window);
runInThisContext inside the code can access external global object, but the outside is actually global object does not exist (although there are, but not intrinsically global objects), just remember one thing, runInThisContext only have access to the very top of the global objects on OK
Execution results are as follows
Copy the code code is as follows:
Object (global present)
11 (the top of the global p)