All about Path in Node
When you first get into
Node, you might be overwhelmed by all the path in this and that regard, especially the notorious
path.resolve. And as if this is not over complex, you also get
. come in as well. So here we go- demystify all of these!
path.join vs path.resolve
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
path.join('/aaa', 'bbb', 'ccc', '/abcd')
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.
(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')
(`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
. used together with libraries like
fs in Node.
__dirname is always the directory in which the currently executing script resides. So if you typed
/aaa/bbb/file.js, the value would be
. gives you the directory from which you ran the
node command in your terminal window — your working directory.
//directory structure is
var path = require("path");
console.log(". = %s", path.resolve("."));
console.log("__dirname = %s", path.resolve(__dirname));//Scenario 1
//what you do
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:
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.