Created
February 10, 2011 23:00
-
-
Save weaver/821554 to your computer and use it in GitHub Desktop.
Use stack introspection to determine the filename of a calling script.
This file contains 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
// An example of how to use stack introspection to determine the | |
// filename of a calling script. | |
// | |
// node stack1.js | |
// | |
function blah() { | |
require('./stack2'); | |
} | |
blah(); |
This file contains 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
// See stack1.js | |
function peek(which) { | |
try { | |
// Throw a dummy error to capture a stack trace. | |
throw new Error('peek'); | |
} | |
catch (e) { | |
// Split the stack trace into lines. Each line ends with a filename: | |
// | |
// at method (file:line:column) | |
// ... | |
// | |
// If the filename is absolute (ignore "node.js") and isn't this | |
// file, return it. | |
var probe, trace = e.stack.split(/\n/); | |
which = which || 0; | |
for (var i = 0, l = trace.length; i < l; i++) { | |
if ((probe = trace[i].match(/\((\/[^:]+):\d+:\d+\)$/)) | |
&& probe[1] != __filename | |
&& --which < 0) | |
return probe[1]; | |
} | |
return undefined; | |
} | |
} | |
console.log(peek()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment