# How to get the current directory in Node.js

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Apr 1, 2020, updated Oct 1, 2022. Topics: Node.js.
Canonical URL: https://attacomsian.com/blog/nodejs-get-current-directory

> A short article to learn how to get the current working directory in a Node.js application.

In Node.js, there are two built-in ways to get the current directory. You can use the `__dirname` variable or the `process.cwd()` method to get the current folder. However, there is a big difference between these two options.

The `__dirname` variable (double underscores at the start) is part of core Node.js since the beginning. It returns the **absolute path of the directory** in which the currently executing JavaScript file exists.

On the other hand, the `process.cwd()` returns the **current working directory** from where you started the Node.js application (e.g. `$ node index.js`).

Here is a simple example:

```bash
node-runner
  ├──index.js
  ├──public
  ├──api
  │  ├──routes.js
  │  └──helpers
  │      └──paths.js
  ├──mailer
  │  └──send-email.js
  └──package.json
```

Let us say the `paths.js` file contains the following code snippet:

<p class="file-desc"><span>paths.js</span></p>

```javascript
console.log(__dirname)
console.log(process.cwd())
```

Now, if you execute the `paths.js` from the root directory, you should see the following output:

```bash
/home/attacomsian/node-runner/api/helpers
/home/attacomsian/node-runner
```

As you can see above, `__dirname` returned the absolute folder path where the execution file (`paths.js`) resides. Whereas `process.cwd()` simply prints the current working directory from where the Node.js application was launched.

The global `__dirname` variable is beneficial when you want to get the current containing folder for a file. For example, when creating a new directory inside the current directory, you can use this variable to specify the absolute parent folder path:

```javascript
const fs = require('fs')
const path = require('path')

// new folder absolute path
const dirPath = path.join(__dirname, '/views')

// create directory
fs.mkdirSync(dirPath)
```

Read [this guide](https://attacomsian.com/blog/reading-writing-files-nodejs) to learn more about reading and writing files in a Node.js application.
