Get the current directory/folder in Node Js

In this short article, we will see how to get the string representation of the current folder or directory name in the filesystem using Node Js.

In Node, there are two ways to get the current directory:

  1. Using module-level variable __dirname
  2. Using in-built process.cwd() method

Let’s check how to find the current path of the folder using the above-mentioned ways.

Get the current directory using __dirname

The __dirname is a special variable in node js which gives us the absolute path of the directory in which the current javascript file is executed.

Let’s say this is my project file structure.

demo-example
  ├──src
  │  ├──index.js
  │  └──api
  │      └──person.js
  └──package.json

And now we will run the index.js file in the src folder. To get the path of the directory we will use the __dirname variable like this.

console.log('Current directory', __dirname)

Output:

/Users/Izz/demo-example/src

It prints out the path of the current directory starting from the root in our console.

Get the current directory using process.cwd() method

The process.cwd() method returns us the current working directory in which the node process is currently taking place.

The process object is a part of the global object called ‘global’ in Node. It gives information about the current process in Node.

Now using the same folder structure as above we will try to get the current directory using process.cwd().

demo-example
  ├──src
  │  ├──index.js
  │  └──api
  │      └──person.js
  └──package.json

Here, we will execute the person.js file in api sub-directory.

console.log('Current dir', process.cwd()) // "/Users/Izz/demo-example"

Difference between __dirname and process.cwd() in Node

Let’s console log the same person.js file in api sub-folder in the project directory.

console.log('Current dir', process.cwd())
console.log('Current dir', __dirname)

Output:

"/Users/Izz/demo-example"

"/Users/Izz/demo-example/src/api"

As you can see the difference between the two is that the process.cwd() returns the path of the project directory starting from the root, whereas the __dirname returns the absolute path of the directory in which the file is currently executed.

Get the current folder/directory name in Node

To get only the current directory name and not the full absolute path in Node Js we have to use the in-built path module.

const path = require("path");

const currentDir = path.basename(__dirname);
console.log(currentDir) // src

The path module provides us with the basename() method. It returns the current name of the folder in which the file is executed. It does not return the full path of the directory.

Since we are running the script file (index.js) in “/demo-example/src” folder, the basename() method returns src (directory name) as output.