__dirname
: This gives us the path from the OS to the folder in which you used it. (important is folder here because we used this command in some file that reside inside that folder)
FOR EXAMPLE: C:\Users\Lenovo\Desktop\Fun\routes\shop.js
this is the path in which we used __dirname
then we will going to get path upto
C:\Users\Lenovo\Desktop\Fun\routes\
__filename
: This command when used gives the full path from OS to the file in which we used it.
So for above example we will get C:\Users\Lenovo\Desktop\Fun\routes\shop.js
Now we know that node js ships with it a core module that is path
module.
let's consider the code snippit below assuming that we are in C:\Users\Lenovo\Desktop\Fun\routes\shop.js
file
const path = require("path");
console.log(path.dirname(__filename))
and the output is :C:\Users\Lenovo\Desktop\Fun\routes
hence the path.dirname()
function just removes the name of file from the path.
My mentor in Node project taught me a way to get the directory name from where our node app is starting. and the code looks like this:
const path = require("path");
module.exports = path.dirname(require.main.filename);
But I found that require.main
object contains a property named path
which is excatly same when we compute it using the second line of code of my mentor.
Hence my code looks like
module.exports = require.main.path;
and it does the same work.
that's it, pretty simple but I haven't created a gist for so long hence thought to create for this one.