Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the VM module in Node.js

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use the VM module in Node.js". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use the VM module in Node.js.

Reference vm virtual machine | Node official website

Http://nodejs.cn/api/vm.html

In the last article, we mentioned a problem.

How can a string become a JS execution?

We introduce two methods in detail, which are eval function and new Function.

We need to emphasize here that functions created by the Function constructor do not create closures for the current environment, they are always created in the global environment, so at run time they can only access global variables and their own local variables, not variables in the scope where they were created by the Function constructor. This is different from the code that uses eval to execute the creation function.

Global.a = 100; / / hanging to the global object global var b = 200; / / this! = = globalnew Function ("console.log (a)") () / / 100new Function ("console.log (b)") () / / b is not defined

Function can get global variables, so he may still have variable contamination. Function is the implementation principle of the module engine, which I will explain in a separate article later.

There is another solution that we did not expand in detail in the last article, which is the vm module.

Vm module

In the above text, I have been emphasizing a concept, that is, variable pollution.

The characteristic of VM is that it is not affected by the environment, or it can be said that it is a sandboxed environment (sandboxed mode provides an environment for modules to run without affecting other modules and their private sandboxes).

Const vm = require ('vm') global.a = 100 console.log scope / run in the current environment [current scope] vm.runInThisContext (' console.log (a)'); / / 100 hand / run in the new environment [other scope] vm.runInNewContext ('console.log (a)'); / / an is not defined

Here we want to emphasize that because global variables are shared under multiple modules in Node.js, try not to define properties in global. The definition in Demo is for ease of understanding.

Suppose we have a file 1.js in the sibling directory that defines global.a = 100;. Now let's introduce this file.

Requrie (. / 1); console.log (a); / / 100

We can find that we do not define the variable an in the current file, but just associate the two module files together. As I mentioned above, global variables in Node are shared among multiple modules.

His principle is that in the environment of Node, there is an execution context in the global.

/ / simulate the global environment of Node / / vm.runInThisContext executes in the current global environment, but does not generate new functions-function (exports, module, require, _ _ dirname, _ _ filename) {/ /...}-vm.runInThisContext. / / vm.runInNewContext executes vm.runInNewContext outside the global environment.

Therefore, vm.runInThisContext can access global variables on global, but not custom variables. While vm.runInNewContext does not have access to global or custom variables, it exists in a completely new execution context.

And we require is realized through vm.runInThisContext.

Implementing require can be divided into the following four steps.

Read the files that need to be imported.

After reading the file, encapsulate the code into a function.

Convert it to JS syntax through vm.runInThisContext.

Code calls.

Suppose we now have the following two files. They are a.js and b.js.

/ / File an exports a variable through module.exports and receives it using require in file b. / / a.jsmodule.exports = "a" / / b.jslet a = require ('. / a'); console.log (a); / / a

We can use the above four steps to analyze what the import and export implementation logic looks like.

Read the file.

This is what happens when the contents of the files that need to be introduced are introduced into the files that need to be received.

Let a = module.exports = "a"

But in this form, Node can't parse at all, so we need to take the second step.

Encapsulate the read file into a function.

Let a = (function (exports, module, require, _ _ dirname, _ _ filename) {module.exports = "a"; return module.exports}) (. Args) / / exports, module, require, _ _ dirname, _ _ filename pass in five parameters

We can refer to the following example for the reason why it is encapsulated as a function.

Suppose what we are passing in is not a string, but a function.

/ / a.jsvar a = 100 per module.cake = function () {}

In this way, when we parse, we will be parsed into the following format

Let a = (function (exports, module, require, _ _ dirname, _ _ filename) {var a = 100; module.exports = function () {}; return module.exports}) (. Args) / / exports, module, require, _ _ dirname, _ _ filename pass in five parameters

We are exporting module.exports, so the variable a defined in the module file only belongs to the current execution context.

When parsing, the variable an is put into the function. The real separation of scopes is achieved.

Vm.runInThisContext is parsed into executable Js code

The code we have processed will exist as a string, so we need to parse the string through vm.runInThisContext.

Make code calls

Before that, we actually need to debug the code.

At this point, I believe you have a deeper understanding of "how to use the VM module in Node.js". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report