本文介绍了检测是通过require调用还是通过命令行直接调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何检测使用SH:node path-to-file
还是JS:require('path-to-file')
调用了Node.JS文件?
How can I detect whether my Node.JS file was called using SH:node path-to-file
or JS:require('path-to-file')
?
这是相当于我在Perl中上一个问题的Node.JS:
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?
推荐答案
if (require.main === module) {
console.log('called directly');
} else {
console.log('required as a module');
}
这篇关于检测是通过require调用还是通过命令行直接调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!