node.js 检测是通过 require 调用还是直接通过命令行调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6398196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect if called through require or directly by command line
提问by Bryan Field
How can I detect whether my Node.JS file was called using SH:node path-to-fileor JS:require('path-to-file')?
如何检测我的 Node.JS 文件是使用 SH:node path-to-file还是 JS:调用的require('path-to-file')?
This is the Node.JS equivalent to my previous question in Perl: How can I run my Perl script only if it wasn't loaded with require?
这是 Node.JS 等价于我之前在 Perl 中的问题:如果我的 Perl 脚本没有加载 require,我如何才能运行它?
回答by nicolaskruchten
if (require.main === module) {
console.log('called directly');
} else {
console.log('required as a module');
}
See documentation for this here: https://nodejs.org/docs/latest/api/modules.html#modules_accessing_the_main_module
请参阅此处的文档:https: //nodejs.org/docs/latest/api/modules.html#modules_accessing_the_main_module
回答by Thorsten Lorenz
There is another, slightly shorter way (not outlined in the mentioned docs).
还有另一种略短的方法(未在提到的文档中概述)。
var runningAsScript = !module.parent;
var runningAsScript = !module.parent;
I outlined more details about how this all works under the hood in this blog post.
我在这篇博文中概述了有关这一切如何运作的更多细节。
回答by bob
I was a little confused by the terminology used in the explanation(s). So I had to do a couple quick tests.
我对解释中使用的术语有些困惑。所以我不得不做几个快速测试。
I found that these produce the same results:
我发现这些产生相同的结果:
var isCLI = !module.parent;
var isCLI = require.main === module;
And for the other confused people (and to answer the question directly):
对于其他困惑的人(并直接回答问题):
var isCLI = require.main === module;
var wasRequired = !isCLI;
回答by Lucio Paiva
Just like in Python, I always find myself trying to remember how to write this goddamn code snippet. So I decided to create a simple module for it. It took me a bit to develop since accessing caller's module information isn't straighforward, but it was fun to see how it could be done.
就像在 Python 中一样,我总是发现自己在努力记住如何编写这个该死的代码片段。所以我决定为它创建一个简单的模块。我花了一些时间来开发,因为访问调用者的模块信息不是直接的,但是看到它是如何完成的很有趣。
So the idea is to call a module and ask it if the caller module is the main one. We have to figure out the module of the caller function. My first approach was a variation of the accepted answer:
所以这个想法是调用一个模块并询问它是否调用者模块是主要的。我们必须弄清楚调用者函数的模块。我的第一种方法是接受答案的变体:
module.exports = function () {
return require.main === module.parent;
};
But that is not guaranteed to work. module.parentpoints to the module which loadedus into memory, not the one calling us. If it was the caller module which loaded this helper module into memory, that's fine. But if it wasn't, we're helpless. So we need to try something else. My solution was to generate a stack trace and get the caller's module name from there:
但这并不能保证有效。module.parent指向将我们加载到内存中的模块,而不是调用我们的模块。如果是调用者模块将这个辅助模块加载到内存中,那很好。但如果不是,我们就无能为力了。所以我们需要尝试其他的东西。我的解决方案是生成堆栈跟踪并从那里获取调用者的模块名称:
module.exports = function () {
// generate a stack trace
const stack = (new Error()).stack;
// the third line refers to our caller
const stackLine = stack.split("\n")[2];
// extract the module name from that line
const callerModuleName = /\((.*):\d+:\d+\)$/.exec(stackLine)[1];
return require.main.filename === callerModuleName;
};
Now we can do:
现在我们可以这样做:
if (require("./is-main-module")()) { // notice the `()` at the end
// do something
} else {
// do something else
}
Or more readable:
或更易读:
const isMainModule = require("./is-main-module");
if (isMainModule()) {
// do something
} else {
// do something else
}
Impossible to forget :-)
不可能忘记 :-)
回答by Kebot
Try this if you are using ES6 modules:
如果你使用 ES6 模块,试试这个:
if (process.mainModule.filename === __filename) {
console.log('running as main module')
}

