How to make node.js execute some code only if my file is an executable?

I want me to be able to run my express server directly through:

$ node app.js 

But I also want to be able to request this file and return an instance of the application, but not actually start the server. Then I can start later with some options.

 app = require './app' app.listen options.someCustomPort 

I'm basically looking for the equivalent of this ruby ​​snippet, but in node.js.

 if __FILE__ == $0 app.listen options[:some_custom_port] end 

Is there an idiom for this?

+7
source share
1 answer

Check

 module.parent 

If it is null or undefined , you are the main file. If not, you were require d. Your module.parent is the module object of the module , which require d you.

+8
source

All Articles