Difference between __dirname and process.cwd() in Node.js

When working with file paths in Node.js, you will frequently encounter __dirname and process.cwd(). While both of these utilities return absolute directory paths, they point to different locations depending on how and where your application is executed. This article explains the fundamental differences between the two, illustrates their behavior with practical examples, and outlines when to use each.

What is __dirname?

__dirname is an environment variable (specifically, a local variable available in every CommonJS module) that returns the absolute path of the directory containing the currently executing JavaScript file.

What is process.cwd()?

process.cwd() is a built-in method of the global Node.js process object. It returns the absolute path of the Current Working Directory (CWD) of the Node.js process—in other words, the directory from which you ran the node terminal command.

Illustrative Example

To understand the practical difference, consider the following directory structure:

/my-project
├── app.js
└── src/
    └── helper.js

Inside src/helper.js, we write the following code:

console.log('__dirname:    ', __dirname);
console.log('process.cwd():', process.cwd());

Depending on where you run the Node.js process, the output will change:

Case 1: Running the script from the project root (/my-project)

If your terminal is in /my-project and you run the script using its relative path:

node src/helper.js

Output: * __dirname: /my-project/src (Points to the location of helper.js) * process.cwd(): /my-project (Points to where you ran the command)

Case 2: Running the script from the src directory (/my-project/src)

If you navigate into the src directory and run the script directly:

cd src
node helper.js

Output: * __dirname: /my-project/src (Remains unchanged) * process.cwd(): /my-project/src (Changes to reflect your current terminal folder)


Comparison Summary

Feature __dirname process.cwd()
Definition Directory of the current script file Current working directory of the process
Scope Module-level variable (CommonJS) Global process method
Dependability Stable (relative to the file location) Dynamic (relative to terminal execution location)
ES Modules Compatibility Not available by default in ES modules (requires workaround) Fully supported in both CommonJS and ES modules

When to Use Which