Skip to content

Instantly share code, notes, and snippets.

@weaver
Created February 10, 2011 23:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weaver/821554 to your computer and use it in GitHub Desktop.
Save weaver/821554 to your computer and use it in GitHub Desktop.
Use stack introspection to determine the filename of a calling script.
// An example of how to use stack introspection to determine the
// filename of a calling script.
//
// node stack1.js
//
function blah() {
require('./stack2');
}
blah();
// 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