我有这样的代码:
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。
你为什么不应该这样做?因为
err.stack
的确切格式尚未正式指定,- 如果您从 native 代码调用此函数,它将失败,
- 这不是设计错误堆栈的目的,
- 它强制执行特定目录,如果您重构代码,这可能会导致问题。
关于javascript - 如何找出函数中的模块路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34691291/