Last active
December 16, 2015 23:39
-
-
Save narqo/5515587 to your computer and use it in GitHub Desktop.
How to get file/method info in JavaScript code. For example for logging
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
/* jshint expr:true, boss:true, node:true */ | |
var backtrace = new Error().stack.split('\n'); | |
var i = 0, line, parts; | |
while(line = backtrace[i++]) { | |
if(line.indexOf(__dirname) === -1) { | |
continue; | |
} | |
parts = line.match(/^\s+at (?:(.*) \()?(.+):([0-9]+):([0-9]+)\)?$/); | |
break; | |
} | |
backtrace = parts.slice(-4); | |
console.log(backtrace); |
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
[ 'Object.<anonymous>', '/Users/varankinv/workspace/backtrace.js', '3', '17' ] | |
---^ ---------^ ------^----^ | |
method file position |
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
/* jshint expr:true, boss:true, node:true */ | |
function getStack() { | |
var orig = Error.prepareStackTrace; | |
Error.prepareStackTrace = function(err, stack) { | |
return stack; | |
}; | |
var err = new Error(); | |
Error.captureStackTrace(err, arguments.callee); | |
var stack = err.stack; | |
Error.prepareStackTrace = orig; | |
return stack; | |
} | |
(function A() { | |
var frame = getStack(), | |
i = 0, | |
f; | |
while(f = frame[i++]) { | |
//console.dir(f); | |
console.log('\033[31;40m' + f.getFunctionName() + '\033[0m '); | |
console.log(f.getLineNumber()); | |
} | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi for more info about V8 Stack Trace API