Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 644
Alex Wayne Avatar asked Dec 09 '11 19:12

Alex Wayne


People also ask

How do I run a single file in node JS?

The usual way to run a Node. js program is to run the globally available node command (once you install Node. js) and pass the name of the file you want to execute. While running the command, make sure you are in the same directory which contains the app.

How do I stop a node script from running?

Method 1: Using ctrl+C key: When running a program of NodeJS in the console, you can close it with ctrl+C directly from the console with changing the code shown below: Method 2: Using process. exit() Function: This function tells Node. js to end the process which is running at the same time with an exit code.

How do I make sure node JS is running?

In windows you can simply go to the Task Manager and check for node in the application list. If it is there then it is running in the machine.


1 Answers

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.

like image 81
Trevor Burnham Avatar answered Oct 06 '22 04:10

Trevor Burnham