Nodejs Express Debug on VSCode

Tram Ho

Debugging a small NodeJS application or a suspected problematic function can be easily debugged with simple methods. However, in an Express application, when the problem cannot be located to a single function or block , we can easily debug end-to-end using the VSCode debugger .

The prerequisites to practice the example in this article are:

  1. An Express application is available
  2. Postman to trigger the request
  3. Installed Nodemon
  4. Since typescript is used in the example, ts-node must also be installed.

The code used in the example below can be found here .

Let’s talk about the logic of this example

For each user , the confirmation date will be in the data. If the user ‘s status has been requested, the application will return ” Active ” if the user’s confirmation date is within the last 365 days, otherwise the status will be returned as ” Inactive “.

Request : GET/user-status/:userId

Set up VSCode Debugger

All configure set up on VSCode Debugger will be in .vscode/launch.json . You can automatically generate this launch file using “ create a launch.json file ” highlighted in the image below and choose configure Node-Js which you can replace later or create your own launch.json file launch.json and add below code.

Automatically generate launcher.json . file

Configure is an array of objects. You can add many configure like debug Unit Test , Debug Chrome for user interface , etc. For our example we will use Node.js: Nodemon Setup .

Selecting Install Nodemon will add configure below.

Sometimes in the project this app.ts file will also be located in another location, then you will also configure it accordingly.

Let’s start debugging

I have now set a breakpoint in the app.ts file as shown below and the debug is started by clicking nút màu xanh lục in the Debug panel . Once the debug is ready, fire a GET request from Postman . The debugger will now reach our breakpoint .

Debug

As you may have noticed, hovering over the userId will show its value . Also, adding it to the WATCH on the left side will display the value as long as it’s in the scope of the current context.

Clicking the down arrow (3rd option) in the điều khiển Debug , takes us into the getUserStatus function. Once in we get the user information and suppose we have to change the commit date to another date to tái hiện Bug or simply want to test it out.etc We can easily do so by how to select “ Set Value ” in the field right-click menu.

When the debug is complete, clicking Play in điều khiển debug will take you to the next breakpoint if there is one, otherwise you will get the response in Postman .

Roundup

As always, I hope you enjoyed this article and learned something new.

Thank you and see you in the next posts!

If you find this blog interesting, please give me a like and subscribe to support me. Thank you.

Ref

Share the news now

Source : Viblo