【问题标题】:Depth of the call-stack调用堆栈的深度
【发布时间】:2014-04-12 23:34:32
【问题描述】:

有没有办法知道 Node.js 中调用堆栈的当前深度?

在 Java 中,我是这样做的:

int depth = Thread.currentThread().getStackTrace().length;

然后我可以用它来记录日志,像这样:

myLogger.writeLogMessage(depth, message);

其中“writeLogMessage”使用深度参数来创建一个格式良好的方法调用树。

现在我想在Node.js中做同样的事情,但是我不知道,如何计算深度?

【问题讨论】:

    标签: node.js logging stack


    【解决方案1】:

    错误对象有一个名为“stack”的getter,它返回一个包含堆栈跟踪的字符串。 REPL 中的示例:

    > console.log(Error().stack)
    Error
        at Error (<anonymous>)
        at repl:1:14
        at REPLServer.self.eval (repl.js:110:21)
        at Interface.<anonymous> (repl.js:239:12)
        at Interface.EventEmitter.emit (events.js:95:17)
        at Interface._onLine (readline.js:202:10)
        at Interface._line (readline.js:531:8)
        at Interface._ttyWrite (readline.js:754:14)
        at ReadStream.onkeypress (readline.js:99:10)
        at ReadStream.EventEmitter.emit (events.js:98:17)
    

    您应该能够通过计算行数来计算深度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-04
      • 2018-02-11
      • 2017-09-16
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 2012-01-13
      相关资源
      最近更新 更多