在 node 中.JS文件中,我发现一句话是这样说的
当文件直接从 node 运行时.js,
require.main
设置为
我想问这里的main
是什么,我在源代码中找不到这main
的定义,有人能帮忙吗,谢谢!
在 node 中.JS文件中,我发现一句话是这样说的
当文件直接从 node 运行时.js,
require.main
设置为
我想问这里的main
是什么,我在源代码中找不到这main
的定义,有人能帮忙吗,谢谢!
require
是一个函数..main
是该函数的属性,因此可以引用require.main
.您所指的文档的这一部分说明您可以编写如下代码:
if (require.main === module) {
// this module was run directly from the command line as in node xxx.js
} else {
// this module was not run directly from the command line and probably loaded by something else
}
在上面的代码中,module
是一个变量,它被传递给 node 加载的所有模块.代码基本上说,如果require.main
是当前模块,那么当前模块就是从命令行加载的模块.
设置该属性的代码如下:https://github.com/nodejs/node/blob/master/lib/internal/modules/cjs/helpers.js#L44.