node.js相当于python的if __name__ =='__main__'

我想检查我的模块是否被包含或直接运行。 我怎么能在node.js中做到这一点?

文档描述了另一种方式来做到这一点,这可能是首选的方法:

当一个文件直接从Node运行时,require.main被设置为它的模块。

要利用这一点,请检查这个模块是否是主模块,如果是这样,请调用您的主代码:

var fnName = function(){ // main code } if (require.main === module) { fnName(); } 

编辑:如果您在浏览器中使用此代码,您将收到“引用错误”,因为“要求”未定义。 为了防止这种情况,使用:

 if (typeof require != 'undefined' && require.main==module) { fnName(); } 
 if (!module.parent) { // this is the main module } else { // we were require()d from somewhere else } 

编辑:如果您在浏览器中使用此代码,您将收到“引用错误”,因为“模块”未定义。 为了防止这种情况,使用:

 if (typeof module != 'undefined' && !module.parent) { // this is the main module } else { // we were require()d from somewhere else or from a browser }