Skip to content Skip to sidebar Skip to footer

When Using Node's Fs.readfile(), Should I Prepend The Path With __dirname?

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 __d

Solution 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.

Solution 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.

Post a Comment for "When Using Node's Fs.readfile(), Should I Prepend The Path With __dirname?"