Debugging Node.js using Visual Studio Code

I've been coding on servers using Node.js for a few years, and the way I've been debugging my code was using console.log('>>> BLA: ', JSON.stringify(...)). How many times have you done that? 😤

Until more recently I came across a feature while using Microsoft Visual Studio Code: Debugging my code with breakpoints!! 🎉

As you can see in the video:

  • I have my server running (inside a separate terminal window). An iOS app running on the side.

  • First, I click that ▶️ button in Visual Studio Code to start the debugging session, and pick the process that my server is on. (more on that later)

  • That attaches to the existing process, which is the separate terminal window where your server is running.

  • When I trigger the api call from the iOS app, I hit my customer server endpoint.

  • Voilà! The control is transferred to Visual Studio Code, where you can inspect all kinds of variables and step through the code! 🎉

Benefits

  • No more console logging (OMG 😅)

  • You can attach to the server at any point, without having to terminate it first and re-launch.

  • Enjoy faster and happier coding 👨🏻‍💻

Setup

  • Hold CMD + P to bring the file navigator.

  • Type: `debug `, it will prompt you to select from the list of projects you have in the workspace.

  • Pick your server project (in my case rest-api), which will create a launch.json file.

  • I selected the “Attach to Process” option.

 

In case VSC automatically picks an alternative way of debugging, you can click on the top/left and select “Add Config (rest-api…)”

Then pick the “Attach to Process” option.

Content of my launch.json file:

{
 // Use IntelliSense to learn about possible attributes.
 // Hover to view descriptions of existing attributes.
 // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
 "version": "0.2.0",
 "configurations": [
   {
     "type": "node",
     "request": "attach",
     "name": "Attach by Process ID",
     "processId": "${command:PickProcess}",
     "skipFiles": [
       "/**"
     ],
     "port": 10000
   }
 ]
}
  • Now you can click the ▶️ to attach to your existing server process.

  • You can then detach, then reattach if needed.

 

I hope you found this post useful, please subscribe for more content 🍻

KB

👨🏻‍💻 Developer 👨🏻‍💼 Entrepreneur 👨🏻‍🎨 Indie Artist 📷 Photographer

https://karlboghossian.com
Previous
Previous

An Introduction to WebSockets with Node.js and React

Next
Next

Organize Files Into Directories by Creation Date using a Node.js script