调用堆栈的深度

时间:2014-04-12 23:34:33

标签: node.js logging stack

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

在Java中,我这样做了:

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

然后我可以用它来记录,如下:

myLogger.writeLogMessage(depth, message);

其中" writeLogMessage"使用depth参数创建一个格式良好的方法调用树。

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

1 个答案:

答案 0 :(得分:2)

错误对象有一个名为“stack”的getter,它返回一个包含堆栈跟踪的String。 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)

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

相关问题