Subtle difference between __dirname and process.cwd() in node.js

Subtle difference between __dirname and process.cwd() in node.js

Getting the current working directory(CWD) is one of the basic and most important features in a product. In Node.js, CWD can be obtained with either __dirname variable or process.cwd(). But the output returned by each command differs based on the folder location where the node command is invoked.

__dirname returns the path where the js file that is being executed is present, whereas process.cwd() returns the path where node command is invoked

Consider this basic example,

$HOME/Documents/cwd.js

console.log(__dirname);
console.log(process.cwd());

When the above js is invoked from $HOME, the output will be

test@test:~$ node Documents/cwd.js

/home/test/Documents

/home/test

If node command is invoked from $HOME/Documents, the output of both command will be same

test@test:~$ node Documents/cwd.js

/home/test/Documents

/home/test/Documents

The difference is so minimal that can lead to a sleepless night if not handled properly.