我如何检测我的node .JS文件是否被调用使用SH:node path-to file或JS:require('path-to file')?

这是Node.JS等价于我之前在Perl中的问题:我怎么能运行我的Perl脚本,如果它没有加载require?


当前回答

如果你正在使用ES6模块,试试这个:

if (process.mainModule.filename === __filename) {
  console.log('running as main module')
}

其他回答

我对解释中使用的术语有点困惑。所以我做了几个快速检查。

我发现它们产生了相同的结果:

var isCLI = !module.parent;
var isCLI = require.main === module;

对于其他困惑的人(并直接回答这个问题):

var isCLI = require.main === module;
var wasRequired = !isCLI;

还有另一种稍短的方法(没有在提到的文档中列出)。

var runningAsScript = !module.parent;

我在这篇博客文章中概述了更多关于这些工作原理的细节。

如果你正在使用ES6模块,试试这个:

if (process.mainModule.filename === __filename) {
  console.log('running as main module')
}
if (require.main === module) {
    console.log('called directly');
} else {
    console.log('required as a module');
}

请在这里查看相关文档:https://nodejs.org/docs/latest/api/modules.html#modules_accessing_the_main_module

我如何检测我的node.js文件是否直接从控制台(windows和unix系统)调用或使用ESM模块导入(import {foo} from 'bar.js')加载 这样的功能没有公开。目前,您应该将cli和库逻辑分离到单独的文件中。

来自node.js核心贡献者devsnek的回答:nodejs/help/issues/2420

在我看来这是正确的答案