Getting Started with Node.js - Module Loading Mechanism

1 Introduction

The content of this article comes from bilibili dark horse programmers

2 Module loading mechanism

2.1 Prioritize loading from cache

模块在第一次加载后会被缓存. This also means that multiple invocations require()will not cause the module's code to be executed multiple times.

Note: Whether it is a built-in module, a user-defined module, or a third-party module, they will be loaded from the cache first, thereby improving the loading efficiency of the module.

2.2 Loading mechanism of built-in modules

Built-in modules are modules officially provided by Node.js, 内置模块的加载优先级最高.
For example, require('fs') always returns the built-in fs module, even if there is a package with the same name in the node_modules directory called fs.

2.3 Loading mechanism of custom modules

  • When using require() to load a custom module, it must be ./specified ../starting with or 路径标识符.
  • When loading a custom module, if ./no ../path identifier such as or is specified, Node.js will load it as a built-in or third-party module.
  • At the same time, when using require() to import a custom module, if the file extension is omitted, Node.js will try to load the following files in order:
  1. load by exact filename
  2. Complete the .js extension for loading
  3. Complete the .json extension for loading
  4. Completing the .node anti-extension name for loading
  5. Failed to load terminal error

2.4 Loading mechanism of third-party modules

  • If the module identifier passed to require() is not a built-in module and does ./not ../start with or , Node.js will try to load third-party modules from the node_modules folder, starting in the current module's parent directory.
  • If the corresponding third-party module is not found, move to the next parent directory and load it until the root directory of the file system.
    For example, assuming require('tools') is called in the "C:\Users\iheima\project\foo.js' file, Node.js will look in the following order:
  1. C:\Users\itheima\project\node_modules\tools
  2. C:\Users\itheima\node_modules\tools
  3. C:\Users\node_modules\tools
  4. C:\node_modules\tools

2.5 Directories as modules

When passing a directory as a module identifier to require() for loading, there are three loading methods:

  1. Find a file called package.json in the loaded directory, and look for the main attribute as the entry for require() loading
  2. If there is no package.json file in the directory, or the main entry does not exist or cannot be resolved, Node.js will try to load the index.js file in the directory.
  3. If the above two steps fail, Node.js will print an error message on the terminal, reporting the absence of the module: Error: Cannot find module 'xxx'

Guess you like

Origin blog.csdn.net/weixin_36757282/article/details/128661056