Wednesday, July 1, 2020

how to use build-in debugger to debug a Node.js appliation?

it is very important to trouble shot an issue or bug in the application development. i will show you how to use the debug tools that built into Node, that let you step through the code.

step 1. add debugger; before the line that you want to debug

 show: (reqresnext=> {
    let userId = req.params.id;
    User.findById(userId)
      .then(user => {
        debugger;
        res.locals.user = user;
        next();
      })
      .catch(error => {
        console.log(`Error fetching user by ID: ${error.message}`);
        next(error);
      });
  },



step 2. run node --inspect-brk main.js command in your project's terminal window to launch the build in debugger

C:\code\Node\unit5\recipe_app (master) (capstone@1.0.0)
λ node --inspect-brk main
Debugger listening on ws://127.0.0.1:9229/d66cdcb4-12df-4f71-80db-43d9c5ba6adc
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.

step 3. launch the chrome browse and type chrome://inspect in the url window.









click on the inspect link. it will start breaking at the first line of main.js









you can either go to line by line with press F10 function or key or press the continue button to go the the line of code with debugger;












you can also go to the node tab under source section, then you can pick anything javascript files to set the breakpoint in order to inspect or trace the code and values








now you can easily fix the trouble code.








No comments:

Post a Comment