Recently, I have been using Nodejs for almost all my projects, one of the most well-liked backend technologies available today. After a few projects with Nodejs, I soon realized that most developers like myself use to have trouble identifying the subtle difference between two of node's global objects, thus __dirname and process.cwd().
Now, lets look at what these global variables are and how they differ in their works.
Node.js has got a global object called global, and the process object lies inside the global object.
process.cwd() gives the name of the directory inside which the NodeJS app is being served from. In other words, the working directory of the NodeJS process.
- In a node Application, I have App.js as my entry file in the root directory
Run app.js on the terminal
======== process.cwd()========= C:\Users\qbentil\blog6 ======== __dirname========= C:\Users\qbentil\blog6
- Create the following project structure
code snippet in try/try.js
code snippet for app.js
run node app.js
======== process.cwd() from /try/try.js========= C:\Users\User\Desktop\blog6 ======== __dirname from /try/try.js========= c:\Users\User\Desktop\blog6\try PS C:\Users\User\Desktop\blog6>
The above output shows that the directory of the file try.js is at blog6/try whereas the current node process is running in blog6/ folder.
Even though the above scope variables, it is important to note the following differences to know which variable to invoke at any point in your application
|It returns the directory name of the directory containing the source code file.||It returns the name the of current working directory where the NodeJS process is being served from.|
|It depends on the current directory.||It depends on the invoking node command.|
|It is local to each module.||It is the node’s global object.|
As a NodeJS developer, It is very important to know how to use these variables as it can be very confusing sometimes and invoke unnecessary bugs in your app.
Let me know your questions or suggestions in the comment box below