Search code examples
javascriptnode.jsdirectory-structure

Finding the location of a file that calls a function (nodejs)


If a method of a module is called from within a file, can I tell the location of that file from within the module? So

// my-module.js
module.exports  = {
  method: function () {
    // in here I would like to detect the path to my-app.js
  }
}

// my-other-module.js
require('my-module').method();

I want some equivalent of access to __filename for my-other-module.js from within my-module.js. I don't want to have to pass __filename as a parameter


Solution

  • For a utility logging you could use this (I used something like this):

    module.exports  = {
        method: function () {
            var myError = new Error();
            var trace = myError.stack.split('\n');
            trace = trace[1];
    
            var filename = trace.substr(trace.lastIndexOf('/') + 1);
            filename = filename.substr(0, filename.indexOf(':'));
    
            console.log('filename', filename);
      }
    };
    

    In my case, I saved "e.stack" because you have all error trace (all files trace). Be carefull with that way, because if you move this code to a function called "getFilename" then you need to modify something the code (because trace will be different, maybe in this example of moving the code with trace = trace[2] will be enough).

    Updated: Add repo example on github

    https://github.com/josemato/stackoverflow/tree/master/js-error-trace-get-filename