问题
Example:
fs.readFile(path.join(__dirname, 'path/to/file'), callback);
versus
fs.readFile('path/to/file', callback);
Both seem to work, so I'm wondering if I can just skip the __dirname prefix, i.e. if there is any reason to prepend it.
回答1:
From the node docs,
__dirname
is the name of the directory that the currently executing script resides in.
This will allow for flexibility across multiple deployments (eg: development / production).
If you are not deploying to any remote servers, you probably don't need the __dirname tag.
回答2:
It is often better to use __dirname because it won't care where node is running from (i.e. the cwd).
Try running your application from a different directory - the __dirname variant will still succeed while the other will not. I.e. instead of node app.js run node foo/app.js assuming app.js lives in a directory named foo.
来源:https://stackoverflow.com/questions/23175779/when-using-nodes-fs-readfile-should-i-prepend-the-path-with-dirname