Get working directory name and file name in Node

__dirname : full directory path
__filename: exact file location

Node provides two variables named “__dirname” and “__filename” who returns the directory path of the currently executing file and the exact location of the file respectively. Both of them return string. To know in depth go through the following.

Get working directory path

We can get the working directory path using the following node global variable.
__dirname
It gives you the full path of the directory containing the current running script.

 __dirname

It returns a string value. Returns the complete resolved path of the directory that the currently executing script resides in.

Suppose, I’m executing node MyAppFile.js which is located in D://MyApps/MyTestApp/
In this case __dirname will return you “D://MyApps/MyTestApp/

__dirname is not actually a global variable. It’s local to each module.

 __dirname vs ./

In the program “./” also indicates the current directory; so does __dirname. So does “./” and “__dirname” do exactly the same thing?

The answer is NO.

Let’s describe with a small example:

Suppose I have my node code in MyAppFile.js, which is located in the following path:
D://dir1/dir2/MyAppFile.js

code of MyAppFile.js:

var path = require("path");
console.log("./ = %s", path.resolve("./"));
console.log("__dirname = %s", path.resolve(__dirname));

Now run the MyAppFile.js in two different ways and compare the outputs:

Way 1:

  1. Navigate to “D://dir1/dir2/MyAppFile.js”
  2. Run with: node MyAppFile.ja

You will get a output:

./ = D://dir1/dir2
__dirname = D://dir1/dir2

Your working directory is D://dir1/dir2 so that is why “./” resolves to. Since MyAppFile.js is located in D://dir1/dir2 that’s what __dirname resolves to as well.

Way 2:

  1. Navigate to “D://dir1/”
  2. Run with: node dir2/MyAppFile.ja

You will get a output:

./ = D://dir1
__dirname = D://dir1/dir2

Your working directory is D://dir1 so that is why “./” resolves to. Since MyAppFile.js is located in D://dir1/dir2 that’s what __dirname resolves to the exact directory location where the file is located.

About This Author

Hello! I am Paul Shan, a JavaScript Expert, Full Stack and DevOps Engineer cum Consultant based out of Bengaluru, India.