Michael Seltenreich Michael Seltenreich - 2 months ago 11
Node.js Question

Running node only works correctly from app directory

When I run node from my app directory, namely:

/var/www/html/
node server.js


The site runs correctly.

When I try to start node from a different directory it runs, but has a wrong root:

#(not in /var/www/html)
node /var/www/html/server.js


What happens is that the correct file is being executed, but all the paths get messed up. Here's an error for example:

GET /auth/login 500 32.511 ms - 2206
Error: Failed to lookup view "login" in views directory "/home/ec2-user/views"


The error is not surprising because the view "login" is not found in

/home/ec2-user/views


but in

/var/www/html/views


How can I correct this behavior?

Clarification:

I am asking this question because I am trying to set up forever to run node on upstart.
The service is successfully runs on upstart, but runs into the same problem manually starting the server does.

Answer

This will most likely happen if you define paths like e.g. for the template engine like:

app.set('views', './views');

With the . it looks up the directory from where you launched the app.

You need to use __dirname like:

app.set('views', __dirname + '/views');

in order to search the views directory in the script's folder. As also explained here: What is the difference between __dirname and ./ in node.js?

Comments