Skip to content

Instantly share code, notes, and snippets.

@Boorj
Last active January 17, 2020 07:20
Show Gist options
  • Save Boorj/e9942ede6793842cd39c29a696d30b9b to your computer and use it in GitHub Desktop.
Save Boorj/e9942ede6793842cd39c29a696d30b9b to your computer and use it in GitHub Desktop.
JS: get stack trace
/**
* getStack
*
* @param {string | string[]} [excludeStr] - substrings that will mark stack line to be excluded
* @return {{
* method ?: string,
* url : string,
* line : number,
* column : number,
* }[]|[]}
*/
export function getStack(excludeStr ) {
const originalStack = new Error().stack;
if (!originalStack)
return [];
const resultStack = [];
originalStack.split("\n").slice(1).forEach(function(line) {
const matches = line.match(/^ +at (?:([\w.]+) \()?([^()]+?)(?::(\d+))?(?::(\d+))?\)?$/);
if (!matches)
return;
if (excludeStr) {
const check = [].concat(excludeStr);
for (const ignoreString of check) {
if (line.includes(ignoreString))
return;
}
}
resultStack.push({
method : matches[1],
url : matches[2],
line : matches[3] && parseInt(matches[3], 10),
column : matches[4] && parseInt(matches[4], 10)
});
});
return resultStack;
}
console.table(getStack(['node_modules', 'internal/process']));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment