How to get the current directory in Node.js

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:

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:

paths.js

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

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

/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:

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 to learn more about reading and writing files in a Node.js application.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.