3

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.

3
  • My guess would be something similar to require("path").dirname(__filename)
    – robertklep
    Commented Dec 9, 2015 at 8:24
  • interesting.. another global variable.. I wonder where are all these coming from? Also, i tried to print out the value of __filename in a test script, it gave me the absolute path of the file. So my next question would be.. how is __filename implemented?
    – arvind
    Commented Dec 9, 2015 at 9:24
  • 2
    Probably start here.
    – robertklep
    Commented Dec 9, 2015 at 9:29

1 Answer 1

1

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.

8
  • Yes, I understand that they are available globally. but then how is it implemented in way that they behave in such a way?
    – arvind
    Commented 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
    – mayank
    Commented Dec 9, 2015 at 6:30
  • He wants the code behind __dirname in the Node source. Commented Dec 9, 2015 at 6:37
  • 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.
    – arvind
    Commented 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 .
    – mayank
    Commented Dec 9, 2015 at 8:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.