Node.js 需要模块
在NodeJS中,每个 JavaScript 文件都被视为一个单独的模块。它使用commonJS模块系统: require() 、 exports和module.export 。
require()模块导出的主要对象是一个函数。当 Node 使用文件路径作为函数的唯一参数调用 require()函数时,Node 将执行以下步骤序列:
- 解析和加载
- 包装
- 执行
- 退货出口
- 缓存
让我们更详细地看一下每个步骤。
- 解析和加载:在此步骤中,节点使用以下步骤决定加载核心模块或开发者模块或第 3 方模块的模块:
- 当 require函数接收到模块名称作为其输入时,它首先尝试加载核心模块。
- 如果 require函数中的路径以'./'或'../'开头,它将尝试加载开发者模块。
- 如果没有找到文件,它会尝试查找包含 index.js 的文件夹。
- 否则它将转到node_modules/并尝试从这里加载模块。
- 如果仍未找到文件,则会引发错误。
- 包装:一旦模块被加载,模块代码将被包装在一个特殊的函数中,该函数将允许访问几个对象。
文件夹结构:
示例 1:
module2.js
// Caching
const mod = require('./module1.js')
module1.js
console.log(require("module").wrapper);
module1.js
console.log("Hello GEEKSFORGEEKS");
module.exports = ()=> console.log("GeeksForGeeks is the best !!");
module2.js
// Caching
const mod = require('./module1.js');
mod();
mod();
mod();
模块1.js
console.log(require("module").wrapper);
输出:
[
'(function (exports, require, module, __filename, __dirname) { ',
'\n});'
]
- 执行:在这部分中,模块的代码或包装函数内部的代码由 NodeJS 运行时运行。
- Returning Exports:在这部分,require函数返回所需模块的导出。这些导出存储在module.exports 中。
使用 module.exports 导出单个变量/类/函数。如果要导出多个函数或变量,请使用导出(exports.add = (a,b)=>a+b)。
退货出口
- 缓存:最后,所有模块在第一次加载后都会被缓存,例如,如果您多次需要相同的模块,您将得到相同的结果。因此代码和模块在第一次调用中执行,在随后的调用中,从缓存中检索结果。
示例 2:让我们举个例子来理解缓存
模块1.js
console.log("Hello GEEKSFORGEEKS");
module.exports = ()=> console.log("GeeksForGeeks is the best !!");
模块2.js
// Caching
const mod = require('./module1.js');
mod();
mod();
mod();
输出:
Hello GEEKSFORGEEKS
GeeksForGeeks is the best !!
GeeksForGeeks is the best !!
GeeksForGeeks is the best !!
![](https://mangodoc.oss-cn-beijing.aliyuncs.com/geek8geeks/Node.js_require_Module_3.jpg)
当我们在 Node,js 中 require() 一个模块时会发生什么