Does this mean that either or are the same? From what I understand, I should use .resolve() when I want an absolute path, but can’t I just easily do this with joining ___dirname to other paths as well?
It depends upon the value of the __dirname (__dirname is defined in the CommonJS modules of NodeJS API).
Suppose __dirname, it is a variable, has a value of “a”. Then, your code will return different values for path1 and path2. Its true that the initial and default value of the __dirname is defined as “The directory name of the current module.”.
The join simply concatenates the supplied path strings. In your code the __dirname has an absolute path value.
The resolve always generates an absolute path using the provided path strings. In case, the first path string is an absolute path, it will use it. That was the case with your code.
For resolve, in case the none of the provided paths is an absolute path, the absolute path is derived from the current directory.
I don’t think so, if I were to change __dirname, then both path1 and path2 would still be the same. Could you clarify on this point?
This is what I was saying, if join is making a new string that is an absolute path, what’s different than using resolve (since resolve is already used to make absolute paths)?
path.join doesn’t make an absolute path by itself. Since, the __dirname variable has an absolute path value, the join returned an absolute path. If __dirname has a relative path (not an absolute path), then join returns a relative path only.
join just “concatenates” the supplied path strings with appropriate path separator (/ for Linux and \ for Windows, for example).
Maybe you can try this code from your console (just save the code in a file called testing_paths.js and run from your terminal, as node testing_paths.js) and review the results.
var path = require('path');
console.log('__dirname ->', __dirname);
var path1 = path.join('dir1', 'dir2', 'dir3');
console.log('path1 ->', path1);
var path2 = path.resolve('dir1', 'dir2', 'dir3');
console.log('path2 ->', path2);
var path1a = path.join(__dirname, path1);
console.log('path1a ->', path1a);
var path2a = path.resolve(__dirname, path1);
console.log('path2a ->', path2a);
var path2b = path.resolve();
console.log('path2b ->', path2b);
var path1b = path.join();
console.log('path1b ->', path1b);
var dirname = 'new_dir';
var path1c = path.join(dirname, path1);
console.log('path1c ->', path1c);
var path2c = path.resolve(dirname, path1);
console.log('path2c ->', path2c);