Debug Node.js App

Introduction
 
In this blog, we are going to see how to debug a node.js app.
 
Previously, in node.js, debugging could be done using the debug command.
 
Note

"Debug" is now deprecated since the latest version. We can use inspect instead.
 
How to use Inspect in node.js
 
Inspect is a completely Graphical User Interface(GUI) based debugger that allows us to enable inspector engine to inspect our application or a script file. By default, it listens to the default port and address:.0.0.1:9229. Still, you can specify your own.

To use inspect, we simply can use the code as below.
  1. node --inspect MyApp.js // Your file name  
Well, there are so many command line options available to use. 
 

Using inspect
 
For that, I have created one JavaScript file.
  1. // Using Core node.js package HTTP  
  2. var http = require('http');  
  3. // Creating HTTP Server  
  4. var server = http.createServer(function(req, res) {  
  5.    res.writeHead(200);  
  6.    res.end('<h1>C#Corner</h1>');  
  7.    console.log("Writing In Console !!!");  
  8. });  
  9. // Specifying Custom Port Number  
  10. server.listen(5555);  
In this, I am going to print the text in response with port number 5555.

Now, open cmd and just paste the following command.
  1. node inspect MyApp.js 
Now, open chrome://inspect/#devices,
 
 
As you can see my script file, MyApp.js, is connected for debugging purposes.
 
Now, let's see how breakpoint works. You need to write it in the console like this.
  1. node --inspect-brk MyApp.js  
After execution, all the information will be given to you like this: 
 
 
 
When you open Developer tools window you can see that debugging is already started :
 
 
It always breaks on the first line of the script when using --inspect-brk. So, this way, you can carry on with debugging with node app 
 
With CLI debugger there are plenty of options available,
  • cont - for continuation inspecting app or a script
  • step - how many steps you want to jump
  • next - next statement or breakpoint to be jumped
  • out - to step out
  • pause - to pause at a specific point.
So this way, you can see how to get started with inspect and with different options.
 
Try it yourself and do let me know if I missed something.