bjskistad bjskistad - 1 month ago 13
Node.js Question

Get __dirname that module is running in?

Is there a way that my module can get the

__dirname
of the file it is running a function in? Something like:

module.js

module.exports.dir = function(){
console.log(__dirname);
}


file.js

var module = require("./module.js");
module.dir();
// /home/user/dir/file.js instead of /home/user/dir/module.js

Answer

You can get the main module(the module that imports the current module) name and using path module you can get the dir of it

const {dirname} = require("path");
module.exports.dir = function () {
    console.log(dirname(require.main.filename))
}

here if module was run on its own require.main.filename will be equal to itself however if its imported it will give you the name of its importer

Comments