访问主模块
¥Accessing the main module
当文件直接从 Node.js 运行时,则 require.main 被设置为其 module。这意味着可以通过测试 require.main === module 来确定文件是否被直接运行。
¥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.
对于文件 foo.js,如果通过 node foo.js 运行,则为 true,如果通过 require('./foo') 运行,则为 false。
¥For a file foo.js, this will be true if run via node foo.js, but
false if run by require('./foo').
当入口点不是 CommonJS 模块时,则 require.main 为 undefined,且主模块不可达。
¥When the entry point is not a CommonJS module, require.main is undefined,
and the main module is out of reach.