Here is some sample code from three files:
// foo.js
var myFunc = require("./myFunc");
function foo(){
myFunc("message");
}
// bar.js
var myFunc = require("./myFunc");
function bar(){
myFunc("message");
}
// myFunc.js
module.exports = myFunc;
function myFunc(arg1){
console.log(arg1);
// Here I need the file path of the caller function
// For example, "/path/to/foo.js" and "/path/to/bar.js"
}
I need to get the file path of the caller function dynamically, without any extra argument passing, for myFunc.
You need to fiddle with the inner workings of
v8. See: the wiki entry about the JavaScript Stack Trace API.I’ve based a little test on some code in a proposed commit and it seems to work. You end up with an absolute path.
And a test that includes
omfgmodule:And you will get on the console the absolute path of
test.js.EXPLANATION
This is not so much a “node.js” issue as it is a “v8” issue.
See: Stack Trace Collection for Custom Exceptions
Error.captureStackTrace(error, constructorOpt)adds to theerrorparameter astackproperty, which evaluates by default to aString(by way ofFormatStackTrace). IfError.prepareStackTrace(error, structuredStackTrace)is aFunction, then it is called instead ofFormatStackTrace.So, we can override
Error.prepareStackTracewith our own function that will return whatever we want–in this case, just thestructuredStackTraceparameter.Then,
structuredStackTrace[1].receiveris an object representing the caller.