查找调用函数的文件的位置(nodejs) [英] Finding the location of a file that calls a function (nodejs)

查看:71
本文介绍了查找调用函数的文件的位置(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();

我希望从my-module.js中获得对my-other-module.js的 __ filename 的等效访问权限.我不想通过 __ filename 作为参数

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

推荐答案

对于实用程序日志记录,您可以使用此命令(我使用了类似的命令):

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

就我而言,我保存了"e.stack",因为您具有所有错误跟踪(所有文件跟踪).请谨慎行事,因为如果将此代码移至名为"getFilename"的函数,则需要修改该代码(因为trace会有所不同,也许在此示例中,使用trace = trace [2]来移动代码)足够).

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).

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

这篇关于查找调用函数的文件的位置(nodejs)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆