I am quite new to Node.js and have come across the "__dirname" and found it to be quite handy for getting the absolute directory path of the script. But I am curious as to how it is implemented, how is it able to understand the directory structure. I have gone through the node js source code but I am not able to find a proper answer.
1 Answer
these object are available globally to use in node create a file anywhere in your system with any name suppose app.js and write in that file
console.log(__dirname);
run it like :-
node app.js
it will print the path of current directory.
-
Yes, I understand that they are available globally. but then how is it implemented in way that they behave in such a way?– arvindCommented Dec 9, 2015 at 6:28
-
arvind please clarify your statement clearly, i mean if this is printing the current directory path in your code then what else you want to do ,i mean what is your requirement– mayankCommented Dec 9, 2015 at 6:30
-
-
I want the internal implementation of __dirname, how is it able to give the directory value dynamically, how is this global populated? Say for example __dirname = getDirName(), where getDirName is a function which populates it, how is this function implemented? hope it makes sense.– arvindCommented Dec 9, 2015 at 6:38
-
look in your basic file create a variable global.__basePath = __dirname and use it in your application to define the path dynamically like __basePath/your file name .– mayankCommented Dec 9, 2015 at 8:04
require("path").dirname(__filename)