在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.您所指的文档的那部分说您可以编写如下代码:
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 }
上面代码中的模块是一个传递给node.js加载的所有模块的变量,因此代码基本上说如果require.main是当前模块,那么当前模块就是从命令行加载的模块.
设置该属性的代码如下:https://github.com/nodejs/node/blob/master/lib/internal/modules/cjs/helpers.js#L44.