All about Path in Node

A short note about path.join path.resolve __dirname and .

Image for post
Image for post
Photo by Viktor Talashuk on Unsplash

path.join vs path.resolve

path.join

path.join('/aaa', 'bbb', 'ccc', '/abcd') 
//====> '/aaa/bbb/ccc/abcd'
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.

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store