Reputation: 627
I have such code:
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();
Is it possible to find out from which file function of module A is called? I know that I can pass __filename param:
var A = require('./A.js');
A(__filename);
but maybe there is another way without passing any params to A()?
Upvotes: 1
Views: 208
Reputation: 707328
If I understand your question properly, then the answer is No. A function in Javascript does not know the filename of its caller in any standard way that is documented in a specification. There are some hacks using the exception stack trace, but it is not recommended to use that for a variety of reasons.
You don't explain why you're trying to do this, but in general a function should not change its behavior based on who the caller is. Rather a function should have a defined behavior based on the arguments passed to it. If you want a different behavior when called from B.js and from C.js, then you should specify some argument when calling it in each circumstance that indicates what the behavior should be or create different functions that can be called to generate the different behaviors.
Upvotes: 1
Reputation: 7771
Well, it is possible, but you really should not do this. You can examine the error stack to get the calling file path like this:
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;
}
}
The parameter n
means how many levels of the stack should be skipped, in your example it should be 1.
Why shouldn't you do this? Because
err.stack
has not been specified formally,Upvotes: 1