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.