javascript - 如何找出函数中的模块路径

标签 javascript node.js function

我有这样的代码:

A.js

module.exports = function() {
/*
    Here I need to find out the path of module in which this function was called.
*/
};

B.js

var A = require('./A.js');

A();

C.js

var A = require('./A.js');

A();

是否可以查到模块A的函数是从哪个文件调用的?我知道我可以传递 __filename 参数:

var A = require('./A.js');

A(__filename);

但也许还有另一种不向 A() 传递任何参数的方法?

最佳答案

嗯,这是可能的,但你真的不应该这样做。您可以检查错误堆栈以获取调用文件路径,如下所示:

function getCallingFile(n) {
  // Regular expression used to extract the file path
  var exp = / \(([^:]+)(:[^\)]+)?\)$/;
  // Extract line from error stack
  var line = new Error().stack.split('\n')[1 + n];
  // Try to find path in that line
  var m = exp.exec(line);
  if(m) {
    return m[1];
  } else {
    return null;
  }
}

参数 n 表示应该跳过堆栈的多少层,在您的示例中它应该是 1。

你为什么不应该这样做?因为

  1. err.stack 的确切格式尚未正式指定,
  2. 如果您从 native 代码调用此函数,它将失败,
  3. 这不是设计错误堆栈的目的,
  4. 它强制执行特定目录,如果您重构代码,这可能会导致问题。

关于javascript - 如何找出函数中的模块路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34691291/

相关文章:

javascript - 在 jsfiddle 中旋转 Canvas

javascript - Select2 按选项值自动完成

c - 数组、指针和字符串操作

javascript - 在 IE 中使用 prototype.js 下拉

node.js 错误消息 events.js :183 throw er;//Unhandled 'error' event

javascript - npm 启动失败

html - 无法加载资源(css/js)AWS Lambda Express Node

c - 从函数返回矩阵

c++ - 如何像传递未定义函数一样传递未定义方法

javascript - 仅对 webpack 中的某些输出文件使用 chunkhash