访问主模块
【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.】