如何窥探一个nodejs进程

我正在运行需要很长时间的nodejs脚本。 它运行一个很长的循环,并进行一些计算。 最后它会显示答案。 答案可能不是42而是5位数字。 我删除了console.log消息,显示它正在做什么使其运行得更快。

我想知道它有多远。 有没有什么方法可以窥探这个过程,看看它在循环中有多远,或者哪些variables中包含了什么值? 我不想中断它,因为我用time命令运行它来计算得到答案需要多长时间。

花了10亿次,花了9分钟才完成。 你认为需要多长时间才能完成1万亿次循环?

创build一个自定义repl并通过节点程序中的套接字公开它。 然后你可以telnet进入你的进程,你将可以访问任何全局variables以及你暴露给repl上下文的任何东西。 例如:

 var net = require("net") , repl = require("repl"); var counterOfInterest = 0; setInterval(function() { counterOfInterest++; }, 1000); function whatsTheStatus() { return 'process has counted ' + counterOfInterest + ' times' }; net.createServer(function (socket) { var remote = repl.start("remote ➜ ", socket); remote.context.whatsTheStatus = whatsTheStatus; }).listen(8888); 

然后,您可以telnet到您的repl并与您的节点程序交互!

 $ telnet 127.0.01 8888 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. remote ➜ whatsTheStatus() 'process has counted 9 times' remote ➜ whatsTheStatus() 'process hascounted 12 times' 

尝试查找节点检查器并使用断点。

这个问题很老,但我只想补充一些东西。

首先,不推荐使用Node.js来处理这样的CPU密集型任务。 您应该使用更低级或编译的语言,如C或Java。 你会看到很多性能的提高。

如果你反正在Node.js中执行,可能是有条件的console.log ,也就是每百万左右,就像这样。

 if (counter % 1000000 == 0) { console.log('Progress: ' + counter); }