如何让CommonJS模块执行main()(如在Python中)? [英] How to have a CommonJS module execute its main() (as in Python)?
本文介绍了如何让CommonJS模块执行main()(如在Python中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否存在一个在CommonJS模块中运行预定义函数的方法(如Node.js中使用的那样)。我写了几个充当服务/服务器的节点模块。我可以从执行各自main()方法的控制器脚本中运行它们,但我也想自己调用它们,就像我们以前在python中那样。
I wonder if a method exists that would run a predefined function in a CommonJS module (as those used in Node.js). I wrote a couple of node modules that act as services/servers. I can run them from inside a "controller script" executing their respective main() method, but I'd like also to call them by itself, like we are used to do in python.
我认为方法是尝试了解模块是否已经被要求。
I think the way is to try to understand if the module has been REQUIREd or not.
你知道怎么做?
这相当于Python
This is the equivalent in Python
if __name__ == "__main__":
print "Running standalone"
推荐答案
if (require.main === module) {
console.log("running standalone");
}
这篇关于如何让CommonJS模块执行main()(如在Python中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文