访问主模块


当文件直接从 Node.js 运行时,则 require.main 被设置为其 module。 这意味着可以通过测试 require.main === module 来确定文件是否被直接运行。

对于文件 foo.js,如果通过 node foo.js 运行,则为 true,如果通过 require('./foo') 运行,则为 false

当入口点不是 CommonJS 模块时,则 require.mainundefined,且主模块不可达。

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 testing require.main === module.

For a file foo.js, this will be true if run via node foo.js, but false if run by require('./foo').

When the entry point is not a CommonJS module, require.main is undefined, and the main module is out of reach.