nodejs run script from absolute path

I'm writing a simple application in Node.js with Express. The path to my script is like path/to/script/server.js. When I run the script through node server.js and I'm in the above path, everything works perfectly.

When I try to run the script trhough node path/to/script/server.js it gives me the following error:

Error: Failed to lookup view "index.html" in views directory "d:\views"
   at Function.app.render [...]

My views are in path/to/script/views.

How to solve it?

In your path/to/script/server.js use this setting (in place of what you may already have for your views path):

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

The default value for this setting is process.cwd() + '/views', which isn't exactly ideal. However setting it as above will make sure that the views directory is relative to server.js instead of the current working directory.

There are two solutions, both are opinionated.

  1. Use cd path/to/script && node server.js. That will change your current folder to path/to/script and then run server.js. As a result, process.cwd() will return the desired working folder.

    Pros: If there is other code relying on current working folder, it will start working as well.

    Cons: It does not look graceful, and will also change your prompt's location, even if you did not want to. Though it is not omg hacks, and is often used, especially when writing cronjob files and application launchers.

  2. Change your code not to rely on current working directory. That is: app.set('views', __dirname + '/views'); which will return directory name of a script, rather than directory from which your application was launched.

    Pros: is often considered as good practice, does not have side effects.

    Cons: you might have to modify the code in more than one place. Your code then relies on location of server.js to be where views folder is.


Why so? Mainly because working directory is rather an essential information and is often used or your benefit, not only to break things when it is not set properly.

Example of how it could be useful:

Imagine having two sites with same code but different serving content, the code is located in /path/to/code and data is in /sites/www1 and /sites/www2, then the magic can happen:

cd /sites/www1 && node /path/to/code.