Last active
October 25, 2024 22:46
-
-
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
This file contains 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
/** | |
* 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 | 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 trimmedCallerLine = callerLine.split('at ')[1].replace(process.cwd() + '/', ''); | |
const [, fnName, filePath, lineNumber, columnNumber] = | |
trimmedCallerLine.match(/^(?:(.+) \()?file:\/\/([^:]+):(\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