最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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.

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.

Share Improve this question asked Apr 19, 2014 at 21:28 Šime VidasŠime Vidas 186k65 gold badges289 silver badges391 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

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.

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.

发布评论

评论列表(0)

  1. 暂无评论