Get name and line of calling function in node.js

后端 未结 5 808
陌清茗
陌清茗 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:39

    The following code uses only core elements. It parses the stack from an error instance.

    "use strict";
    function debugLine(message) {
        let e = new Error();
        let frame = e.stack.split("\n")[2];
        let lineNumber = frame.split(":")[1];
        let functionName = frame.split(" ")[5];
        return functionName + ":" + lineNumber + " " + message;
    }
    function myCallingFunction() {
        console.log(debugLine("error_message"));
    }
    myCallingFunction();
    

    It outputs something like myCallingFunction:10 error_message

    I've extracted the elements of the error as variables (lineNumber, functionName) so you can format the return value any way you want.

    As a side note: the use strict; statement is optional and can be used only if your entire code is using the strict standard. If your code is not compatible with that (although it should be), then feel free to remove it.

提交回复
热议问题