Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging an infinite loop in node.js

Tags:

node.js

I seem to have an infinite loop somewhere in my node.js program. CPU goes up to 99.9% and the server just freezes.

Is there any way to break when the server freezes and then check the call stack to see what function is causing this?

like image 642
DanielS Avatar asked Sep 05 '11 07:09

DanielS


People also ask

How do you debug an infinite loop?

The best first step for debugging an infinite loop is to comment out different sections or lines of code, then running the program to see where the infinite loop is occurring. Start by testing any sections that contain for or while loops, then if/else statements, then other blocks of code.

How do you stop an infinite loop in node JS?

Use window. stop() to prevent the page from loading and running. For NodeJS only – Use process. abort() or process.

How do you make an infinite loop in Javascript?

We can create an infinite loop using while statement. If the condition of while loop is always True , we get an infinite loop.


2 Answers

So, I figured out a solution.

I installed node-inspector (awesome piece of work BTW) and compiled node in debug mode. Don't forget to activate it: node-inspector & will run it in the background.

After that I started the node process with V8's debug flag:

node --debug script.js

The tricky part was getting the infinite loop to reappear, but after 20 minutes or so I lucked out and it did. I used the inspector's interface to pause the program (pause button on the right hand side) and then check out where the stack is currently is. Sometimes the pause will occur in native code but you can pause and resume it until you go back to the JavaScript.

Success :)

like image 77
DanielS Avatar answered Sep 17 '22 19:09

DanielS


If node-inspector doesn't work for you for some reason (it doesn't for me), but you can easily reproduce the bug, try running node --prof script, wait until it freezes and then a few more minutes, then just run node-tick-processor and see which function has the most ticks.

like image 28
a sad dude Avatar answered Sep 21 '22 19:09

a sad dude