preface

I’ve been looking at Node recently, so I took a special look at its module introduction process. Let’s do a review today, which I hope will be helpful to you as you read

Module classification in node

  1. Core modules, or built-in modules (fs, HTTP, VM…) See the official API for details
  2. Third party modules, or their own packaged NPM package to the private library or public library (NPM via NPM install)
  3. File modules, project internal files, are used by the relative path or absolute path method require

The import of the module require

I use vscode for debugging tools

The process of the require

  1. Return mod.require(path)

2. Enter the mod. The require found is real execution Module. The prototype. The require, (where the id is the beginning of the path), well ~ how again call Module. _load, wood, we continue to walk

  1. Go to module._load (), module._load (id, this, /* isMain */ false) and load the Module according to the path
  • Module._cache: exports the file name as the key of the module. _cache object to see if the file is already cached

  • Module._resolveFilename resolves the file path to an absolute path if it does not exist in the cache array

  • The first two cache lookups exclude external modules, and then determine whether they are built-in modules, and then exports

  • If you go to this point, it really means that this module is not cached, so new one

This.exports = {} : exports = {} : exports = {} : exports = {} : exports = {} : exports = {} : exports = {} : exports = {} : exports = {} : exports = {} : exports = {}

5. Module._cache[filename] The path resolved in Step 3 is used as the key, and the value of the object created in Step 4 is stored in our cache array. Keep going!!!!!

Module.load (), enter the function

  • Filename suffix findLongestRegisteredExtension calculation,

  • Module._extensions[extension](this, filename) calls different load methods based on different suffixes (here using policy mode)

  • Module._compile (content, filename).js (fs.readfilesync).js (fs.readfilesync)

Module._compile (); wrapSafe(filename, content, this)

Ps: I’m going to go directly to the old version, the implementation is easier to understand

  • Wrap is called, and the Node Module is wrapped as a required Module (function (){}) to form a separate Module

  • The returned wrapped string module is then used as the vm.runInThisContext parameter to execute the module code (the same effect as the new Function in JS that makes the string js for execution). See the node official website for details of node’s own built-in methods

9. By default, the user will get the result of module.export

conclusion

  1. Read the file
  2. Wrap a function around a file after it has been read
  3. Function (exports,module,require,_dirname,filename){}
  4. Call the module into JS syntax with runThisContext

Finally, if you find this article helpful, please remember to like three times oh, thank you very much