Difference between process.cwd & _ _dirname in NodeJS

Node.jsServer Side ProgrammingProgramming

NodeJS is a JavaScript runtime environment that was built on top of Chrome's V8 engine. The traditional use of JavaScript is to be executed in browsers, but with Node.JS we can execute JavaScript other than browsers like servers, hardware devices, etc.

process.cwd()

The process object lies under the global object known as 'global'. This method provides information about the current process of Node.js. It also provides control over the same. cwd refers to the current working directory of the same. Therefore, process.cwd returns the working directory on which execution is taking place currently.

__dirname

This is a local module that will return the directory name of the current module. Also, it is a local module

process.cwd__dirname
Returns name of the current working directory.
Returns the name of the directory containing the source code files.
It is a global object inside Node.
It is a local object
It depends on the command which is invoked.
It depends upon the current directory.

process.cwd() vs __dirname

Example 1 (index.js)

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

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

Output

C:\Users\tutorialsPoint\> node index.js.js
process.cwd(): /home/node/demo
__dirname: /home/node/demo

Example 2

Create the following files with the below folder structure

-- src/
   --index.js
   --src2/
      --index2.js

Code Snippet (index.js)

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

Code Snippet (index2.js)

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

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

Run the index2.js file using the following command.

   node index2.js

Output

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

The above output shows that the directory of the file index2.js is at src/src2 whereas the current node process is running in src/ folder.

raja
Published on 27-Apr-2021 12:59:11
Advertisements