Loading mechanism of module

  1. Prioritize loading from cache

    Modules are cached after the first load. This means that multiple calls to require() will not cause the module’s code to be executed multiple times. 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. Loading mechanism of built-in modules

    Built-in modules are modules officially provided by Node.js, and built-in modules have the highest loading priority.

    For example, if a third-party module and a built-in module have duplicate module names, require('module name') always returns the built-in module, even if there is a third-party module package with the same name in the node_modules directory.


  3. Custom module loading mechanism

    When loading a custom module with require(), you must specify a path identifier starting with ./ or ../. When loading a custom module, if no path identifier is specified, node will load it as a built-in module or a third-party module, resulting in a failure to load.

    Also, when importing a custom module using require(), if the file extension is omitted, Node.js will in order to try to load the following files separately:

    1. Load by exact filename

    2. Completing .js extension loading

    3. Completing .json extension loading

    4. Completing .node extension loading

    5. Failed to load, the terminal reports an error


  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 start from the current module’s parent directory, trying to start from the /node_modules file folder to load third-party modules.

    If the corresponding third-party module is not found, it will be moved to the next parent directory and loaded until the root directory of the file system.


  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 property, which serves 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 report an error: Error: Cannot find module 'xxx' .

Share