Details about the VM module in NodeJs and the NodeJsVM Module
What is a VM?
The VM module is the core module in NodeJS. It supports the require method and the operating mechanism of NodeJS. In some cases, we may also need to use the VM template to do some special things.
Through VM, JS can be compiled and immediately executed or compiled and saved for later execution (JavaScript code can be compiled and run immediately or compiled, saved, and run later .)
The VM module contains three common methods used to create a sandbox system that runs independently:
Vm. runInThisContext (code, filename );
This method is used to create an independent sandbox runtime space. The code in the code can access external global objects, but cannot access other variables.
In addition, the code is shared internally by global and externally.
Copy codeThe Code is as follows:
Var vm = require ("vm ");
Var p = 5;
Global. p = 11;
Vm. runInThisContext ("console. log ('OK', p)"); // displays 11
Vm. runInThisContext ("console. log (global)"); // display global
Console. log (p); // display 5
Vm. runInContext (code, sandBox );
This method is used to create an independent sandBox runtime space. sandBox is passed into the code as a global variable, but there is no global variable.
SandBox must be the sandBox created by vm. createContext ().
Copy codeThe 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 is undefined
Console. log (window. p); // changed to 3
Console. log (util. inspect (window ));
Vm. runInNewContext (code, sandbox, opt );
This method should be the same as runInContext, but the steps for creating a sandBox are missing.
Comparison
More complex scenarios
What if runInThisContext is executed in runInContext? Who is the global Object accessed by runInThisContext?
How will the following code be executed?
Copy codeThe 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 );
The code in runInThisContext can access the external global object, but there is actually no global object outside (although there are, it is not actually a global Object). Just remember one thing, runInThisContext can only access the global object at the top.
The execution result is as follows:
Copy codeThe Code is as follows:
Object (global)
11 (top global p)