Get name and line of calling function in node.js

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

    Here is a one liner for quick debugging purposes:

    console.log("DEBUG", (new Error().stack.split("at ")[1]).trim());
    

    This will log something like this with Node.js:

    DEBUG SomeObject.function (/path/to/the/code.js:152:37) 
    

    --

    You can also add custom args at the end, e.g.

    console.log("DEBUG", (new Error().stack.split("at ")[1]).trim(), ">>>", myVar);
    

    Note that if you put this into a helper function, adjust the stack index from e.g. [1] to [2].

提交回复
热议问题