Home >Web Front-end >JS Tutorial >Detailed explanation of VM module in NodeJs_node.js
What is VM?
The VM module is the core module in NodeJS, supporting the require method and the operating mechanism of NodeJS. Sometimes we may also use VM templates to do some special things.
Through VM, JS can be compiled and run immediately or compiled, saved, and run later.
The VM module contains three commonly used methods for creating an independently running sandbox system, as follows:
vm.runInThisContext(code, filename);
This method is used to create an independent sandbox running space. The code within the code can access external global objects, but cannot access other variables
And the code is shared internally and externally
This method is used to create an independent sandbox running space. sandBox will be passed as a global variable into the code, but there is no global variable
The sandBox requirement is the sandBox created by the vm.createContext() method
Compare
More complex situations
What will happen if runInThisContext is executed in runInContext? Whose global object does runInThisContext access?
How will the following code be executed?
The code inside runInThisContext can access external global objects, but there is actually no global object outside (although there is, it is not essentially a global object). Just remember that runInThisContext can only access the top global object.
The execution results are as follows