Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node js/Express js relative paths (dot or __dirname or without any prefix)?

Tags:

I'm looking at Nodejs/expressjs and have seen different tutorials use either __diranme + "/my_folder", "./my_folder", or just "my_folder".

Examples:

app.use("/static", express.static(__dirname + "/my_folder")); app.use("/static", express.static("./my_folder")); app.use("/static", express.static("my_folder")); 

I tried them all and they all seem to work; which one should I use for relative paths?

I've also seen require('./my_file.js') and require('my_file'). Is there a difference? What should I use?

like image 594
Raekye Avatar asked May 24 '13 02:05

Raekye


1 Answers

Almost any function (except for require) which takes file paths as an argument, will at one point use functions from the fs module to read from or write to them.

Node.js documentation for fs module says:

Relative path to filename can be used, remember however that this path will be relative to process.cwd().

When you think about it, it would require major trickery to have these functions behave any differently. After all, the fs functions are regular Javascript and they don't have special access to information about the caller. The only __dirname they could access would be the __dirname of their own module (the core fs module).

The fact that the require function can resolve paths relative to the current __dirname, without specifying this explicitly, is because require is a unique function for every single file it appears in. This way, it has access to the current module's specifics, and in particular its path.

The reason your code happens to work is that currently, the app.js (or similar) the code above appears in happens to be in the same directory as what process.cwd() currently is. I.e. starting the app with node app.js would work, while starting the app with node myappdir/app.js (ran from its parent directory) would not. process.cwd() would be different.

As long as you keep in mind that relative paths will be resolved via process.cwd(), then you could use the shorter syntax. In some cases it can be an advantage. It does make your code dependent on how it's called though. I personally prefer using __dirname, because it's somewhat more transparent as to what's happening, and the relative paths consistent with the paths you use in a require statement for the same file.

like image 136
Myrne Stol Avatar answered Sep 21 '22 14:09

Myrne Stol