NodeJS modularization ④ (module loading mechanism)

Load from cache first

Modules are cached after the first load. This also means that multiple calls to 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.

We can verify this with
a custom module:

console.log('ok')

Execution side:

require('自定义模块')
require('.自定义模块')
require('自定义模块')

Finally our terminal returns:

ok

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, 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.

Loading mechanism for custom modules

When loading a custom module with require(), a path identifier starting with ./ or …/ must be specified. When loading a custom module,If no path identifier such as ./ or .../ is specified, node 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 sequence:
① Load according to the exact file name
② Complete the .js extension Loading
③ Complete the .json extension to load
④ Complete the .node extension to load
⑤ The loading fails, and the terminal reports an error

Loading mechanism for 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 load from the /node_modules folder 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 .

For example:
assuming that require('tools') is called in the 'C:\Users\itheima\project\foo.js' file, Node.js will look for it in the following order:
insert image description here

Directories as modules

When passing a directory as a module identifier to require() for loading, there are three loading methods:
① Find a file called package.json in the loaded directory, and look for the main attribute, which is loaded as require() Entry
② 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.
③ If the above two steps fail, Node.js will print an error message in the terminal to report the missing module: Error: Cannot find module 'xxx'

Guess you like

Origin blog.csdn.net/zyb18507175502/article/details/124298289