Get name and line of calling function in node.js

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

    I found and installed the node-stack-trace module (installed with npm install stack-trace), and then defined echo as:

    function echo() {
      var args, file, frame, line, method;
      args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
    
      frame = stackTrace.get()[1];
      file = path.basename(frame.getFileName());
      line = frame.getLineNumber();
      method = frame.getFunctionName();
    
      args.unshift("" + file + ":" + line + " in " + method + "()");
      return log.info.apply(log, args); // changed 'debug' to canonical npmlog 'info'
    };
    

提交回复
热议问题