Reputation: 15119
According to this question: What is the difference between __dirname and ./ in node.js? these 2 lines should be the same:
require(__dirname + '/folder/file.js');
require('./folder/file.js');
and I always used to use the second option. But now a project, I took over, the previous developer used require(__dirname + ...)
every time.
Personally I thinks it's harder to read and I'd like to change it, but maybe there is some advantage of this syntax I'm missing? Or is it the preferred version and I was doing it wrong all the time?
Just in case it matters, the libraries run sometimes on node.js with es6 enabled and sometimes on io.js (without additional flags).
Upvotes: 1
Views: 647
Reputation: 13577
When using require()
there is no difference, using __dirname
is kind of redundant. The module loader will take care of the resolving the path correctly for you.
When using one of the fs
methods like fs.readFile
there is a difference if your current working directory is not equal to __dirname
. If I want to read contents of a file called file.txt in the same directory as my script, I do:
var Fs = require('fs');
var Path = require('path');
Fs.readFile(Path.join(__dirname, 'file.txt'), ...);
Then it doesn't matter what my cwd is when I start the node process that executes this code.
Upvotes: 3