This article mainly introduces the VM module in Nodejs, this article explains what is VM, VM module Runinthiscontext, Runinthiscontext method and so on, need friends can refer to the following
What is a VM?
The VM module is the core module inside the Nodejs, supporting the Require method and Nodejs operation mechanism, we may also use the VM template to do some special things.
The VM,JS can be executed immediately after compilation or 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 for creating a stand-alone sandbox system, as follows three methods
Vm.runinthiscontext (code, filename);
This method is used to create a separate sandbox run space in which code can access external global objects, but cannot access other variables
and the code internal global and external sharing
The code is as follows:
var VM = require ("VM");
var p = 5;
GLOBAL.P = 11;
Vm.runinthiscontext ("Console.log (' OK ', p)");//Show 11 under Global
Vm.runinthiscontext ("Console.log (Global)"); Show Global
Console.log (P);//Show 5
Vm.runincontext (code, SANDBOX);
This method is used to create a separate sandbox run space in which sandbox will be the global variable passed into the code, but no global variables exist
Sandbox requirements are created by the Vm.createcontext () method sandbox
The 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 with fewer steps to create sandbox
Comparison
A more complicated situation
If Runincontext inside executes Runinthiscontext, who is the global object that Runinthiscontext access to?
How will the following code be executed?
The 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 inside the Runinthiscontext can access external global objects, but there is actually no global object (although there is, but not the global object), just remember that Runinthiscontext can only access top-most global objects OK
Implementation results are as follows
The code is as follows:
Object (Global exists)
11 (P of top global)
Note < > : More Wonderful tutorials please focus on Triple programming