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.
2 Answers
Reset to default 2From 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
.