Skip to content

Instantly share code, notes, and snippets.

@grimen
Last active October 6, 2015 08:08
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 grimen/2963484 to your computer and use it in GitHub Desktop.
Save grimen/2963484 to your computer and use it in GitHub Desktop.
Get caller file path by throwing error and parse the stack trace (in this example for module "rerequire").
var caller_path = undefined; // ...but...but no known native way in Node.js to know what file that triggered the current method.... ='(
try {
// ...so let's break some code of honors! >:)
throw Error();
} catch (err) {
var stack_lines = err.stack.split('\n'),
found_this = false;
for (var i in stack_lines) {
var line = stack_lines[i];
if (!found_this && /rerequire\.js/.test(line)) {
// Tjing 1/2: Found this module!
found_this = true
} else if (found_this) {
if (!/rerequire\.js/.test(line)) {
// Tjing 2/2: Found the module that called this module!
caller_path = line.match(/^[^\/]+([^\:]+)\:/)[1]; // <-- SUCCESS >:)
break;
}
}
}
console.log(caller_path) // ...and mwuaha, we can get the caller file from the stack trace string. >:)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment