Search code examples
node.js

How do I get the dirname of the calling method when it is in a different file in nodejs?


Let's say I have two files, dir/a.js and lib/b.js

a.js:

b = require('../lib/b');
b.someFn();

b.js:

var fallback = "./config.json";
module.exports = {
  someFn = function(jsonFile) {
    console.log(require(jsonFile || fallback);
  }
}

The entire purpose of b.js in this example is to read a json file, so I might call it as b.someFn("path/to/file.json").

But I want there to be a default, like a config file. But the default should be relative to a.js and not b.js. In other words, I should be able to call b.someFn() from a.js, and it should say, "since you didn't pass me the path, I will assume a default path of config.json." But the default should be relative to a.js, i.e. should be dir/config.json and not lib/config.json, which I would get if I did require(jsonFile).

I could get the cwd, but that will only work if I launch the script from within dir/.

Is there any way for b.js to say, inside someFn(), "give me the __dirname of the function that called me?"


Solution

  • Use callsite, then:

    b.js:

    var path = require('path'),
        callsite = require('callsite');
    
    module.exports = {
      someFn: function () {
        var stack = callsite(),
            requester = stack[1].getFileName();
    
        console.log(path.dirname(requester));
      }
    };