Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs: get filename of caller function

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?

like image 557
einstein Avatar asked May 22 '13 17:05

einstein


2 Answers

Failing to restore the prepareStackTrace function can cause issues. Here's an example that removes side-effects

function _getCallerFile() {     var originalFunc = Error.prepareStackTrace;      var callerfile;     try {         var err = new Error();         var currentfile;          Error.prepareStackTrace = function (err, stack) { return stack; };          currentfile = err.stack.shift().getFileName();          while (err.stack.length) {             callerfile = err.stack.shift().getFileName();              if(currentfile !== callerfile) break;         }     } catch (e) {}      Error.prepareStackTrace = originalFunc;       return callerfile; } 
like image 178
Rhionin Avatar answered Sep 17 '22 12:09

Rhionin


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; } 
like image 31
Bagus Budiarto Avatar answered Sep 19 '22 12:09

Bagus Budiarto