使用Node的fs.readFile()时,是否应该在路径前加上__dirname? [英] When using Node's fs.readFile(), should I prepend the path with __dirname?
本文介绍了使用Node的fs.readFile()时,是否应该在路径前加上__dirname?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例:
fs.readFile(path.join(__dirname, 'path/to/file'), callback);
与
fs.readFile('path/to/file', callback);
两者似乎都有效,所以我想知道是否可以跳过__dirname
前缀,即是否有任何理由将其前缀.
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.
推荐答案
使用__dirname通常更好,因为它不在乎节点从何处运行(即cwd).
It is often better to use __dirname because it won't care where node is running from (i.e. the cwd).
尝试从其他目录运行应用程序-__dirname
变体仍然会成功,而另一个则不会. IE.假设app.js
驻留在名为foo
的目录中,而不是node app.js
运行node foo/app.js
.
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
.
这篇关于使用Node的fs.readFile()时,是否应该在路径前加上__dirname?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文