Languages
[Edit]
EN

JavaScript - get method call stack

4 points
Created by:
Marcin
16270

In this short article we want to show how to get method call stack in JavaScript in Google Chrome web browser.

Quick solution:

// ONLINE-RUNNER:browser;

const pattern = /^\s*at\s*(\w*)\s+\(?(.*)\)?\s*$/g;
            
const getCallStack = () => {
    const stack = [];
    try {
        throw new Error(); // exception throwing to get access to call stack
    } catch(e) {
        const parts = e.stack.split('\n');
        for (let i = 2; i < parts.length; ++i) {
            pattern.lastIndex = 0;
            const match = pattern.exec(parts[i]);
            if (match) {
                stack.push({
                    method: match[1],
                    file: match[2]
                });
            }
        }
    }
    return stack;
};

// Usage example:

const method1 = () => {
    const stack = getCallStack();
    console.log('----------------------------');
	console.log(' method1                    ');
	console.log('----------------------------');
	console.log(JSON.stringify(stack[0], null, 2));
	console.log(JSON.stringify(stack[1], null, 2));
	console.log();
};

const method2 = () => {
    const stack = getCallStack();
    console.log('----------------------------');
	console.log(' method2                    ');
	console.log('----------------------------');
	console.log(JSON.stringify(stack[0], null, 2));
	console.log();
    method1();
};

method2();
Getting method call stack in JavaScript example.
Getting method call stack in JavaScript example.
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - friendly IT community for everyone.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join