Get name and line of calling function in node.js

后端 未结 5 812
陌清茗
陌清茗 2020-12-07 08:50

How can one get the name and line of a function that called the current one? I would like to have a rudimentary debugging function like this (with npmlog defining log.

5条回答
  •  渐次进展
    2020-12-07 09:41

    Using info from here: Accessing line number in V8 JavaScript (Chrome & Node.js)

    you can add some prototypes to provide access to this info from V8:

    Object.defineProperty(global, '__stack', {
    get: function() {
            var orig = Error.prepareStackTrace;
            Error.prepareStackTrace = function(_, stack) {
                return stack;
            };
            var err = new Error;
            Error.captureStackTrace(err, arguments.callee);
            var stack = err.stack;
            Error.prepareStackTrace = orig;
            return stack;
        }
    });
    
    Object.defineProperty(global, '__line', {
    get: function() {
            return __stack[1].getLineNumber();
        }
    });
    
    Object.defineProperty(global, '__function', {
    get: function() {
            return __stack[1].getFunctionName();
        }
    });
    
    function foo() {
        console.log(__line);
        console.log(__function);
    }
    
    foo()
    

    Returns '28' and 'foo', respectively.

提交回复
热议问题