Last active
October 6, 2015 08:08
-
-
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").
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
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