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

人盡茶涼 提交于 2021-02-16 15:10:59

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/30336847/finding-the-location-of-a-file-that-calls-a-function-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!