在Node.JS文档中,我找到一句话说
When a file is run directly from Node.js,
require.main
is set to its module. That means that it is possible to determine whether a file has been run directly by testingrequire.main === module
.'
我想问这里的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.js 加载的所有模块,因此代码基本上说如果 require.main
是当前模块,那么当前模块就是从命令行加载的。
设置该属性的代码在这里:https://github.com/nodejs/node/blob/master/lib/internal/modules/cjs/helpers.js#L44 .
关于Node.js, require.main === 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45136831/