如果__name__ =='__main__',则相当于python的node.js [英] node.js equivalent of python's if __name__ == '__main__'
本文介绍了如果__name__ =='__main__',则相当于python的node.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想检查是否包含我的模块或直接运行我的模块.如何在node.js中做到这一点?
I'd like to check if my module is being included or run directly. How can I do this in node.js?
推荐答案
文档描述执行此操作的另一种方法,这可能是首选方法:
The docs describe another way to do this which may be the preferred method:
直接从Node运行文件时,将require.main设置为其模块.
When a file is run directly from Node, require.main is set to its module.
要利用此优势,请检查此模块是否为主要模块,如果是,请调用您的主要代码:
To take advantage of this, check if this module is the main module and, if so, call your main code:
var fnName = function() {
// main code
}
if (require.main === module) {
fnName();
}
如果在浏览器中使用此代码,则由于未定义要求",因此将出现引用错误".为防止这种情况,请使用:
If you use this code in a browser, you will get a "Reference error" since "require" is not defined. To prevent this, use:
if (typeof require !== 'undefined' && require.main === module) {
fnName();
}
这篇关于如果__name__ =='__main__',则相当于python的node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文