javascriptnode.jsnode-repl

Using the Node REPL to log the value of __dirname


If I write a script like containing console.log(__dirname); logs the value of __dirname. But if I try the same for the Node REPL like this happens:

 > console.log(__dirname)
 ReferenceError: __dirname is not defined

Thoughts?


Solution

  • From this What is the difference between __dirname and ./ in node.js? written by d512

    In Node.js, __dirname is always the directory in which the currently executing script resides (see this). So if you typed __dirname into /d1/d2/myscript.js, the value would be /d1/d2.

    The documentation says that __dirname is equal to path.dirname. If you type path.dirname into the repel it tells you this:

    > console.log(path.dirname)
    [Function: dirname]
    undefined
    

    Now my guess is: Since it is a repl, you don't have a file which is stored somewhere on the disk. It simply reads the command, evaluates it and prints it to the console.

    Someone with more experiences on REPLSs might give a longer and detailed answer, but I think this laid out the concept.