Alex Wayne
Alex Wayne

Reputation: 187014

How do I make node.js execute some code only if my file is the running file?

I want to be able to start my express server directly via:

$ node app.js

But I also want to able to require that file, and have it return the app instance but actually not start the server. Then I can start later it 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?

Upvotes: 8

Views: 1220

Answers (1)

Trevor Burnham
Trevor Burnham

Reputation: 77416

Check

module.parent

If it's null or undefined, you're the main file. If not, you've been required. Your module.parent is the module object of the module that required you.

Upvotes: 9

Related Questions