Node.js: difference between __dirname and process.cwd()


process.cwd() returns the directory from which you invoked the node command.

__dirname returns the directory name of the directory containing the JavaScript source code file

Example: you have a project with following folder structure

test
├── index.js
└── lib
    └── lib.js

lib.js

console.log('./lib/lib.js')

console.log(process.cwd())

console.log(__dirname)

index.js

require('./lib/lib.js')

console.log('index.js')

console.log(process.cwd())

console.log(__dirname)

We do 2 cases:

Administrator@MRNC-N9NJM89QFO MINGW64 /d/AppServ/www/node2/test
$ node index.js
./lib/lib.js
D:\AppServ\www\node2\test
D:\AppServ\www\node2\test\lib
index.js
D:\AppServ\www\node2\test
D:\AppServ\www\node2\test

Administrator@MRNC-N9NJM89QFO MINGW64 /d/AppServ/www/node2/test
$ cd /

Administrator@MRNC-N9NJM89QFO MINGW64 /
$ node /d/AppServ/www/node2/test/index.js
./lib/lib.js
D:\Program Files\Git
D:\AppServ\www\node2\test\lib
index.js
D:\Program Files\Git
D:\AppServ\www\node2\test

nodejs process cwd

Leave a Reply