Skip to content

Instantly share code, notes, and snippets.

@nemtsov
Last active December 10, 2015 03:58
Show Gist options
  • Save nemtsov/4378073 to your computer and use it in GitHub Desktop.
Save nemtsov/4378073 to your computer and use it in GitHub Desktop.
Retrieves the filename of the caller of a function.
StackUtil = {};
/**
* Get the filename of the caller of a function
*
* @param {Boolean} options.isLineNumberRendered
* @return {String} name
*/
StackUtil.getCallerFilename = function (options) {
var name, callSite;
options = options || {};
Error.prepareStackTrace = _getCallerCallSite;
callSite = new Error().stack;
Error.prepareStackTrace = undefined;
name = callSite.getFileName()
if (options.isLineNumberRendered) {
name += ':' + callSite.getLineNumber()
+ ':' + callSite.getColumnNumber();
}
return name;
};
function _getCallerCallSite(err, trace) {
// 0: stack_util, 1: caller, 2: caller's caller
return trace[2];
}
module.exports = StackUtil;
@nemtsov
Copy link
Author

nemtsov commented Dec 26, 2013

Calling Error.prepareStackTrace has negative implications on performance. Consider using the following instead:

Error.captureStackTrace(this, this.constructor);
var nativeStack = Object.getOwnPropertyDescriptor(this, 'stack');
var callSite = nativeStack.get();
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment