Nodejs中的require函数的具体使用方法

2020-06-17 06:53:04易采站长站整理

index.js中的内容如下:


let cors = require("cors")
console.log(cors)

运行 node index.js ,得出以下结果:

[Function: middlewareWrapper]

找到node_modules下的cors模块文件夹,观察cros模块中的package.json文件,找到main字段: “main”: “./lib/index.js” ,找到main字段指向的文件,发现这是一个IIFE,在IIFE中的代码中添加,console.log(“hello cors”),模拟代码结构如下:


(function () {
'use strict';
console.log("hello cors"); // 这是手动添加的代码
...
function middlewareWrapper(o) {
...
}
module.exports = middlewareWrapper;
})()

再次运行 node index.js ,得出以下结果:

hello cors
[Function: middlewareWrapper]

为什么会打印出 hello cors 呢?因为require模块的时候,引入的是该模块package.json文件中main字段指向的文件。而这个js文件会自动执行,跟require引用本地js文件是相同的。

packjson文档

在npm的官方网站中可以找到关于package.json中的main字段定义。

main   The main field is a module ID that is the primary entry point to your program. That is, if your package is named foo, and a user installs it, and then does require(“foo”), then your main module’s exports object will be returned.   This should be a module ID relative to the root of your package folder   For most modules, it makes the most sense to have a main script and often not much else.

在以上说明中可以得出以下结论:

main字段是一个模块ID,是程序的主入口。
当使用require(“xxx”)的时候,导入的是main字段对应的js文件里的module.exports。

所以require导入模块的时候,是运行的对应模块package.json中main字段指定的文件。