How to get current folder in Node.js

Jul 20, 2023#node#how-to

There are many reasons why we might need to access the current folder in Node.js such as: read from files, write to files, write logs, load configuration files, load templates, load modules, serve static files, etc.

In Node.js, “current folder” refers to 2 possible locations:

  • Current folder in project, using __dirname variable, which is specific to the location of the script based on project folder structure.
  • Current working directory, process.cwd() method, which is the directory of Node.js process running from, might be different from the script’s location, especially if the script is executed from a different directory using an absolute or relative path.

The main difference between process.cwd() and __dirname is that process.cwd() is global to the Node.js process and can be changed at runtime using process.chdir(), while __dirname is local to each module and is fixed once the module is loaded.

Dot-slash notation (./) is a bit tricky. It represents the current directory where the script is located when used in require() statement. Otherwise it’s similar to process.cwd().

Using __dirname variable

In Node.js, __dirname is a special global variable that represents the absolute path of the directory containing the currently executing script. It provides the full path to the directory where the current script resides.

You can use __dirname in your Node.js applications to construct absolute file paths or to perform file operations relative to the location of the current script.

Here’s an example of how to use __dirname:

Suppose you have the following directory structure:

project/
└── main.js
└── myModule.js
└── subfolder/
    └── data.txt
// myModule.js
const path = require('path');

// Get the absolute path of the 'data.txt' file in the 'subfolder' directory
const dataFilePath = path.join(__dirname, 'subfolder', 'data.txt');

// Now you can use the absolute file path to read the file, write to it, or perform any file operation
console.log('Absolute path to data.txt:', dataFilePath);
// main.js
const myModule = require('./myModule'); // The './' here is relative to main.js

When you run main.js the output will be:

cd /path/to/project
node main.js
# Prints: Absolute path to data.txt: /path/to/project/subfolder/data.txt

As you can see, __dirname in myModule.js provides the absolute path to the directory where myModule.js is located (/path/to/project), and using it, we construct an absolute file path to the data.txt file in the subfolder directory.

Using __dirname is particularly helpful when you need to access files relative to the script’s location, regardless of where the application is executed from. It ensures that your file operations work correctly, even if you run the script from different directories or when the script is included as a module in other files.

Learn more: Fix error “__dirname is not defined in ES module scope”

Using process.cwd() method

In Node.js, you can get the current working directory (current folder) using the process.cwd() method. This method returns the current working directory as a string representing the absolute path of the folder where the Node.js process is currently running.

Here’s an example of how to use process.cwd() in a file:

// /home/user/projects/demo/index.js
const currentFolder = process.cwd();
console.log('Current folder:', currentFolder);

When you run this code, it will log the absolute path of the current working directory to the console. Keep in mind that the current working directory may change depending on how you run your Node.js app. For example:

cd /home/user
node projects/demo/index.js
# Prints: /home/user

cd /home/user/projects/demo
node index.js
# Prints: /home/user/projects/demo

Method process.cwd() is a useful method in Node.js for various scenarios, especially when you need to work with file paths or perform file system operations.

  • To create a new directory or file relative to the current working directory. For example:
// index.js
const fs = require('fs');
const path = require('path');

// create a new directory called logs
const dirPath = path.join(process.cwd(), '/logs');
fs.mkdirSync(dirPath);

// create a new file called app.log inside logs
const filePath = path.join(process.cwd(), '/logs/app.log');
fs.writeFileSync(filePath, 'Hello world');
  • To read a file relative to the current working directory. For example:
// index.js
const fs = require('fs');
const path = require('path');

// read the file config.json from the current working directory
const filePath = path.join(process.cwd(), '/config.json');
const config = JSON.parse(fs.readFileSync(filePath, 'utf8'));
console.log(config);
  • To change the current working directory using process.chdir(). For example:
// index.js
const process = require('process');

// print the current working directory
console.log(process.cwd()); // /home/user/projects

// change the current working directory to my-app
process.chdir('./my-app');

// print the new current working directory
console.log(process.cwd()); // /home/user/projects/my-app

Using dot-slash notation (./)

Dot-slash notation is a convention used in Unix-based operating systems (including Linux and macOS) to represent the current directory. It is used as a relative file path prefix to specify files or directories located in the current working directory of a process or script.

// index.js
const fs = require('fs');

// create a JSON object
const data = {
  name: 'Alice',
  age: 25,
  hobbies: ['reading', 'coding', 'gaming']
};

// write the JSON object to data.json in the current working directory
fs.writeFile('./data.json', JSON.stringify(data, null, 2), (err) => {
  if (err) {
    console.error(err);
  } else {
    console.log('File created successfully');
  }
});

The dot-slash notation is useful when you want to refer to files or directories that are in the same location or nearby to the current working directory, without having to specify the full absolute path. It is also useful when you want to make your paths portable, meaning that they will work regardless of where your files are located, as long as they maintain the same relative structure.

When using ./ in the require statement, it indicates that you want to load a local module relative to the current importing script based on the folder structure. Let’s assume you have the following directory structure:

project/
└── main.js
└── myModule.js
└── subfolder/
    └── mySubmodule.js

In main.js:

const myModule = require('./myModule'); // Loads myModule.js from the current directory
const mySubmodule = require('./subfolder/mySubmodule'); // Loads mySubmodule.js from the subfolder directory