Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

NodeJS is a JavaScript runtime that was built on top of Chrome’s V8 Engine. The traditional JavaScript is executed in browsers but with Node.js we can execute JavaScript on servers, hardware devices, etc.

process.cwd(): Similar to window objects on browsers, Node.js has got a global object called global, and the process object lies inside the global object. This process object provides information about, and control over, the current Node.js process. It gives the current working directory of the Node.js process.

__dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file.

Difference between process.cwd() vs __dirname in Node.js is as follows:

process.cwd() _dirname
It returns the name the of current working directory. It returns the directory name of the directory containing the source code file.
It is the node’s global object. It is local to each module.
It depends on the invoking node command. It depends on the current directory.

Example 1:

index.js




// Logging process.cwd() output
console.log("process.cwd(): ", process.cwd());
 
// Logging __dirname output
console.log("__dirname: ", __dirname);


Run the index.js file using the following command:

node index.js

Output:

process.cwd(): C:\src
__dirname: C:\src

In this case node process is running in the current directory

Example 2: Create the following 2 files with the following folder structure:

src/
___ index.js
___ src2/
___index2.js

FilePath: src/index.js

index.js




// Read and execute the index2.js file
require('./sub1/index2.js')


FilePath: src/src2/index2.js

index2.js




// Logging process.cwd() output
console.log("process.cwd(): ", process.cwd());
 
// Logging __dirname output
console.log("__dirname: ", __dirname);


Run the index.js file using the following command:

node index.js

Output:

process cwd:  C:\src
__dirname: C:\src\src2

This shows that the current node process was running in src/ folder i.e node index.js and the directory of the file index2.js was at src/src2.



Last Updated : 20 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads