调用栈的深度

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

在Java中,我这样做了:

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

然后我可以用它来logging,如下所示:

 myLogger.writeLogMessage(depth, message); 

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

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

错误对象有一个名为“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) 

您应该可以通过计算行数来计算深度。