bjskistad bjskistad - 1 year ago 102
Node.js Question

Get __dirname that module is running in?

Is there a way that my module can get the

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


module.exports.dir = function(){


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

Answer Source

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 () {

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download