This article will give you a detailed introduction to the execution process of require innodejs. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
I was looking at node recently, so I deliberately learned about the process of introducing its modules. Today I will make a review record, I hope it will be helpful to you who are reading
Core module, or built-in Module (that is, the fs, http, vm that comes with node...)For details, please see the official website api
Third-party modules, or use your own encapsulated npm package for private use Library or public library (installed and used through npm install on npm)
File modules, internal files of the project, require using relative paths or absolute paths
[Recommended learning: "nodejs Tutorial"]
My debugging tools The
#1. Read the file and enter the require method return mod.require (path)
#2. Enter mod.require and find that Module.prototype.require is actually executed (the id here is the initial path), um~ Why? Module._load is called, it’s nothing, let’s continue
3. Enter Module._load(),Module._load(id, this, /* isMain */ false) Load the module according to the path
What I hit here is .js. In this method, fs.readFileSync is used to read the file synchronously, and then the module._compile(content, filename) is called as parameters
7. module._compile() enter , and found that content was used as the parameter of wrapSafe(filename, content, this) and executed
8. Then enter wrapSafe() ps: I will talk about the old version directly here, execute It’s easier to understand
9. At this point, the require process of a module has been executed, and the user will get it by default. The return result of module.export
Read the file
Read the file Wrap a function in the file later
Function format function (exports, module, require,_dirname, filename){}
Place the module through runThisContext Turn into js syntax for calling
For more programming-related knowledge, please visit:Introduction to Programming! !
The above is the detailed content of How to import module in nodejs? Introduction to the execution process of require. For more information, please follow other related articles on the PHP Chinese website!