开发者

How to have a CommonJS module execute its main() (as in Python)?

开发者 https://www.devze.com 2023-03-08 04:38 出处:网络
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

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.

Do you know how?

This is the equivalent in Python

if __name__ == "__main__":
   print "Running standalone"


if (require.main === module) {
    console.log("running standalone");
}

accessing the main module

0

精彩评论

暂无评论...
验证码 换一张
取 消