When using Node's fs.readFile(), should I prepend the path with __dirname?

馋奶兔 提交于 2019-12-12 17:18:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!