All about Path in Node
A short note about path.join
path.resolve
__dirname
and .

When you first get into Node
, you might be overwhelmed by all the path in this and that regard, especially the notorious path.join
vs. path.resolve
. And as if this is not over complex, you also get __dirname
and .
come in as well. So here we go- demystify all of these!
path.join vs path.resolve
path.join
Simply put, it just joins all the arguments to a path from left to right using platform specific delimiter, e.g. /
in OS, just like when you call Array.join()
in JavaScript.
path.join('/aaa', 'bbb', 'ccc', '/abcd')
//====> '/aaa/bbb/ccc/abcd'
path.resolve
Instead of simply joining, this resolves all the path arguments into an absolute path. How it does this? Well. it processes arguments from right to left, until an absolute path is created.
If after processing all given path arguments, an absolute path has not been generated, the current working directory is used.
path.resolve('/aaa/bbb', '/ccc/ddd/')
//====> '/ccc/ddd'
(since an absolute path is already created in the first right argument, it won't look at the left path.resolve('aaa', 'bbb/ccc/', '../ddd/file')
//====> '/home_dir/aaa/bbb/ddd/file'
(`bbb/ccc/' + '../ddd/file' will be resolved to 'bbb/ddd/file' since '../ddd/file' will go one directory higher;
'aaa' will be prepended current home directory since it's not an absolute path)
__dirname vs "."
We always see __dirname
and .
used together with libraries like path
and fs
in Node.
__dirname
is always the directory in which the currently executing script resides. So if you typed __dirname
into /aaa/bbb/file.js
, the value would be /aaa/bbb
.
By contrast, .
gives you the directory from which you ran the node
command in your terminal window — your working directory.
//directory structure is
/dir1
/dir2
file.js//file.js
var path = require("path");
console.log(". = %s", path.resolve("."));
console.log("__dirname = %s", path.resolve(__dirname));//Scenario 1
//what you do
cd /dir1/dir2
node file.js//what you get:
. = /dir1/dir2
__dirname = /dir1/dir2//==> Your working directory is /dir1/dir2 so that's what . resolves to. Since file.js is located in /dir1/dir2 that's what __dirname resolves to as well.//Scenario 2
//what you do:
cd /dir1
node dir2/file.js//what you get
. = /dir1
__dirname = /dir1/dir2//===>In that case, you execute the command in a parent directory to your script --/dir1, so that's what . resolved to, but __dirname still resolves to /dir1/dir2 since it's where the script resides.