Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Last Updated : 23 Feb, 2021

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 index2.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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!