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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With