Skip to content

Instantly share code, notes, and snippets.

@chrisdothtml
Last active August 7, 2024 20:19
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 Node.js utility that can be used to determine what function and file your function was called from
/**
* A Node.js 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;
* filePath: string;
* lineNumber: number;
* columnNumber: number;
* } | null}
*/
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 trimmedCallerLine = callerLine
.split('at ')[1]
.replace('file://', '')
.replace(process.cwd() + '/', '');
const [, fnName, filePath, lineNumber, columnNumber] =
trimmedCallerLine.match(/^([^ ]+)\s+\(([^:]+):(\d+):(\d+)\)$/) || [];
if (fnName && 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