Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
63
rated 0 times [  70] [ 7]  / answers: 1 / hits: 24901  / 11 Years ago, wed, may 22, 2013, 12:00:00

I wonder how-to get an absolute path of a caller of a function?



Let say that:



in file a.js I call b(); b() is a function defined in file b.js. a.jsrequires b . So how do I get a.js absolute path from b.js in node?


More From » node.js

 Answers
17

This is an example how to use stacktrace to find caller file in node


function _getCallerFile() {
var filename;

var _pst = Error.prepareStackTrace
Error.prepareStackTrace = function (err, stack) { return stack; };
try {
var err = new Error();
var callerfile;
var currentfile;

currentfile = err.stack.shift().getFileName();

while (err.stack.length) {
callerfile = err.stack.shift().getFileName();

if(currentfile !== callerfile) {
filename = callerfile;
break;
}
}
} catch (err) {}
Error.prepareStackTrace = _pst;

return filename;
}

[#78082] Tuesday, May 21, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
quentinaveryb

Total Points: 102
Total Questions: 100
Total Answers: 93

Location: Colombia
Member since Mon, May 2, 2022
2 Years ago
quentinaveryb questions
Thu, Aug 6, 20, 00:00, 4 Years ago
Fri, Jul 17, 20, 00:00, 4 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;