Created
November 16, 2012 06:14
-
-
Save coltrane/4084714 to your computer and use it in GitHub Desktop.
a function that examines the js call stack to find information about the caller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* examines the call stack (if available) and returns a string | |
* indicating the file and line number of the n'th previous ancestor call. | |
* this works in chrome, and should work in nodejs as well. | |
* | |
* @param n : int (default: n=1) - the number of calls to trace up the | |
* stack from the current call. `n=0` gives you your current file/line. | |
* `n=1` gives the file/line that called you. | |
*/ | |
function traceCaller(n) { | |
if( isNaN(n) || n<0) n=1; | |
n+=1; | |
var s = (new Error()).stack | |
, a=s.indexOf('\n',5); | |
while(n--) { | |
a=s.indexOf('\n',a+1); | |
if( a<0 ) { a=s.lastIndexOf('\n',s.length); break;} | |
} | |
b=s.indexOf('\n',a+1); if( b<0 ) b=s.length; | |
a=Math.max(s.lastIndexOf(' ',b), s.lastIndexOf('/',b)); | |
b=s.lastIndexOf(':',b); | |
s=s.substring(a+1,b); | |
return s; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment