Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...