Node.js provides a built-in debugger that allows us to inspect and debug our Javascript code.
The debugger is based on the Chrome DevTools protocol and provides a powerful set of features for "stepping through code", "setting breakpoints", "inspecting variables", and more.
Inspecting Variables: The debugger allows us to inspect the values of variables at a specific point in our code, which helps to identify their current state.
Stepping Through Code: The debugger allows us to step through line by line in our code, helping us understand the code flow and identify any logical errors or unexpected behaviour.
Setting Breakpoints: we can place breakpoints in our code using the debugger statement, allowing us to pause execution at specific points and inspect the current state of variables.
To enable the debugger, we need to start our Node.js application with the "--inspect" or "--inspect-brk" flag.
The "--inspect" flag starts the debugger without breaking at the first line, while "--inspect-brk" breaks at the first line, allowing you to set breakpoints.
node --inspect server.js or node ----inspect-brk server.js
Note: `server.js` is the entry point file from where our code starts executing. It can be different in your project such as `index.js`, `main.js` etc.
Once your application starts running with the "--inspect" flag, then open your Chrome browser and navigate to chrome://inspect. You should see your Node.js application listed under "Remote Target".
Click on "Open dedicated DevTools for Node" to open the Chrome DevTools for your Node.js application.
Step Over (F10): Executes the current line of code and stops on the next line.
Step Into (F11): If the current line contains a function call, step into the function.
Step Out (Shift + F11): Steps out of the current function to the calling function.
function someFunction() { // Some code to be execute debugger; // Code execution will pause here // More code to be execute }
We can use the debugger statement in our code to pause execution and open the debugger when it is encountered.
we can also use other compatible tools like "Visual Studio Code" for debugging.
Open VS code, open terminal of Visual studio code.
Click on dropdown icon, next to `+` icon on the right-end side of the terminal panel.
Select `javaScript Debugger Terminal`.