Skip to content

Instantly share code, notes, and snippets.

@chrisdothtml
Last active February 19, 2025 00:06
Show Gist options
  • Save chrisdothtml/7fc317d7a6d7ecd14b80d0ad188c2ecf to your computer and use it in GitHub Desktop.
Save chrisdothtml/7fc317d7a6d7ecd14b80d0ad188c2ecf to your computer and use it in GitHub Desktop.
A JavaScript utility that can be used to determine what function and file your function was called from
/**
* A JavaScript utility that can be used to determine what function
* and file your function was called from. Useful for debugging
* large/complex codebases.
*
* @returns {{
* fnName: string | void;
* filePath: string;
* lineNumber: number;
* columnNumber: number;
* } | null}
*/
export function getFnCaller() {
const error = new Error();
if (!error.stack) return null;
// index 0 is the error name
// index 1 is this fn's stack line
// index 2 is the fn that called this fn
// index 3, finally, is the one that called this fn's caller
const callerLine = error.stack.split('\n')[3];
if (!callerLine) return null;
const nodeCwd =
typeof process != 'undefined' && typeof process?.cwd === 'function'
? process.cwd() + '/'
: '';
const trimmedCallerLine = callerLine.split('at ')[1].replace(nodeCwd, '');
const [, fnName, filePath, lineNumber, columnNumber] =
trimmedCallerLine.match(/^(?:async )?(?:(.+) \()?(?:[^:]+:\/\/)?([^:]+):(\d+):(\d+)\)?$/) || [];
if (filePath && lineNumber && columnNumber) {
return {
fnName,
filePath,
lineNumber: parseInt(lineNumber),
columnNumber: parseInt(columnNumber),
};
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment