Skip to content

Instantly share code, notes, and snippets.

@ragingwind
Created October 21, 2020 00:21
Show Gist options
  • Save ragingwind/1a265ab146122848ec13cbc3b1c5d669 to your computer and use it in GitHub Desktop.
Save ragingwind/1a265ab146122848ec13cbc3b1c5d669 to your computer and use it in GitHub Desktop.
Callstack for javascript
import { sep } from 'path';
function splitPath(filename, level: number) {
const paths = filename.split(sep);
return paths.splice(paths.length - level).join(sep);
}
export function caller(level: number) {
const oldStackTrace = Error.prepareStackTrace;
try {
// eslint-disable-next-line handle-callback-err
Error.prepareStackTrace = (err, structuredStackTrace) =>
structuredStackTrace;
Error.captureStackTrace(this);
const callSite = this.stack[level];
return (
splitPath(callSite.getFileName(), 2) + ':' + callSite.getLineNumber()
);
} finally {
Error.prepareStackTrace = oldStackTrace;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment