Page Content

Tutorials

How to Debug Node.js in browser?

Debug Node.js

Any developer who wants to properly identify and fix problems in their code must be able to debug Node.js apps. A wide range of tools, from basic logging to sophisticated interactive debuggers, are available in Node.js for this purpose.

for Debugging

Debugging with console.log statements is the most basic and popular method. Using this approach, you can publish the values of variables or show the execution flow by carefully arranging console.log() statements throughout your code. After passing the parameters to console.log, a new line is displayed to the standard output (stdout). A string representation will be displayed if an object is passed.

Advantages

  1. Simplicity: There is no extra setup needed, and it is easy to use.
  2. Quick Insight: Instant feedback on variable states and code execution pathways is provided by Quick Insight.

Limitations

  1. Manual: Complex problems may require a lot of time to add and remove statements by hand.
  2. Less Flexible: It makes it impossible to pause execution at particular moments without changing the code or to dynamically investigate the status of the application.
  3. Security Risk: If private information is accidentally logged, it could be made public.

Example: To see what’s happening in your code, you can insert a console.log statement:

// Example: Using console.log
console.log('Starting application...'); 
let user = {
    name: 'Alice',
    age: 30
};
console.log('User object:', user); 
function greet(personName) {
    console.log(`Hello, ${personName}!`); 
}
greet(user.name);
console.log('Application finished.');

You may better comprehend the flow and data at various moments by looking at the reported information in your terminal when this script runs.

Node.js Built-in Debugger

A built-in non-graphical debugger in Node.js is available through the command line for more thorough debugging. Because this debugger is based on the robust V8 JavaScript engine the same engine that powers the browser in Google Chrome it enables a thorough examination of the state of your application.

Usually, node debug filename.js or node inspect filename.js are used to launch your application in debug mode. In order to use the built-in V8 inspector, which may be combined with Chrome DevTools to provide a graphical debugging experience, the node inspect command is advised for more recent versions of Node.js (v6.3.0 and up).

The debugger pauses execution at the first line of your script when it first launches. This is the output you’ll see, with a debug> prompt indicating that commands are ready:

< Debugger attached.
Break on start in debugDemo.js:1
> 1 function addTwoNumber(a, b){ // function returns the sum of the two numbers
  2 debugger
  3 return a + b;
debug>

Breakpoints and Watchers

By using breakpoints, which are markers you can insert into your code to halt execution at particular lines, you may analyse the status of the application at that precise instant. You just add the debugger; keyword to the JavaScript code where you want execution to halt in the built-in Node.js debugger.

Example with debugger;: Consider this simple Node.js application (debugDemo.js):

// debugDemo.js
'use strict';
function addTwoNumber(a, b){ // function returns the sum of the two numbers
  debugger; //  The debugger will pause here
  return a + b;
}
var result = addTwoNumber(5, 9);
console.log(result);

To run and debug this file: node debug debugDemo.js.

Watchers provide you insight into how the values of variables or expressions change as your code is executed by allowing you to keep an eye on them as you walk through it.

Basic Debugger Commands

Once the debugger is paused, you can use several commands at the debug> prompt to control execution and inspect variables:

  1. cont or c: Continue execution from the current breakpoint until the next breakpoint or the end of the program.
  2. next or n: Move to the next line of code without stepping into function calls.
  3. step or s: Step into a function. This allows you to inspect the code inside a function that your current line calls.
  4. out or o: Step out of a function. If you’ve stepped into a function, this command takes you back to the calling function when the current function returns.
  5. repl: Enters a Read-Eval-Print-Loop (REPL) mode within the debugger. This allows you to interactively execute JavaScript code in the current scope, inspect variables, and test out lines of code. Press Ctrl+C to exit the debug REPL.
  6. watch(expression): Adds an expression or variable to a watch list. Its value will be displayed whenever the debugger pauses.
  7. unwatch(expression): Removes an expression or variable from the watch list.

Debugging with Chrome DevTools

Google Chrome DevTools can be integrated with the Node.js debugger to provide a more intuitive graphical user experience. This makes use of Chrome’s well-known visual debugging features for web developers.

Use the --inspect or --inspect-brk flag when launching your Node.js application to access Chrome DevTools: node --inspect-brk your-script.js

When the --inspect-brk flag is used, Node.js is instructed to launch the debugger and halt execution at the first line of code. Node.js will provide a URL (such as ws://127.0.0.1:9229/…) when this command is executed.

Next, in your Chrome browser, open chrome://inspect. “Open dedicated DevTools for Node” is the button under the “Devices” category. This will open a new DevTools window with the code for your Node.js application. This is where you can see:

  • Set Breakpoints: Create or remove breakpoints by clicking on line numbers.
  • Inspect Variables: To inspect variables, either hover over them in your code or add expressions to watch using the “Watch” panel on the right.
  • Control Execution: Use the play/pause (c/cont), step over (n/next), step into (s/step), and step out (o/out) buttons to control the execution of your code.

Debugging a Node.js application is similar to working as a detective on a case. Sticky notes with hints at different locations are similar to console.log statements. Instead, the built-in debugger is your own forensic laboratory where you can halt the entire process, analyse all of the evidence (variables), fast-forward or rewind the events (code execution), and determine the precise time at which the problem occurred. You can then visualise all the actions and hints in a much more user-friendly and immersive manner by using Chrome DevTools to create your own sophisticated virtual reality crime scene.

Index