Skip to content

Instantly share code, notes, and snippets.

@pixelhijack
Created October 20, 2014 08:41
Show Gist options
  • Save pixelhijack/475c86b087b4838b7ffb to your computer and use it in GitHub Desktop.
Save pixelhijack/475c86b087b4838b7ffb to your computer and use it in GitHub Desktop.
javascript stack trace anywhere
/*
It's well know how to print a stack trace after catching an exception/error in Javascript.
But what if you are not catching anything?
You see something happening at a particular line in code,
but you want to know what's the code path through which the control flow reached that line when that interesting thing happened.
In other words, you want to know what's the stack trace (series of function calls, starting from beginning of the program),
at that particular line of code.
http://www.codeovertones.com/2011/08/how-to-print-stack-trace-anywhere-in.html
*/
var e = new Error('dummy');
var stack = e.stack.replace(/^[^\(]+?[\n$]/gm, '')
.replace(/^\s+at\s+/gm, '')
.replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@')
.split('\n');
console.log('callstack:', JSON.stringify(stack, null, 2));
/* ~ console.trace() */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment