查找调用函数的文件的位置(nodejs)

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

如果从文件中调用模块的方法,我可以从模块中知道该文件的位置吗?所以

// 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();

我想要从 my-module.js 中为 my-other-module.js 访问 __filename。我不想将 __filename 作为参数传递

对于实用程序日志记录,您可以使用这个(我使用了类似的东西):

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);
  }
};

在我的例子中,我保存了 "e.stack" 因为你有所有错误跟踪(所有文件跟踪)。使用这种方式要小心,因为如果您将此代码移动到一个名为 "getFilename" 的函数,那么您需要修改代码的某些内容(因为跟踪会有所不同,也许在这个使用 trace = trace[2 移动代码的示例中] 就足够了)。

已更新:在 github

上添加回购示例

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