Debugging Node.js via VS code with Attach (single process only)

Saransh Khobragade
Aug 10 · 3 min read

Start debugging Node with powerful VScode

  1. Method 1:(Attach)(light/Fast debugging) Till now you must be starting your node project by hitting “node your.js”,try hitting instead
node --inspect=2000 hello.js

You can use any terminal you want you can attach your debugger to 2000.

  • Check on left there is bug sign on VS code click on that its debug mode.
  • Click on setting icon of launch program.
  • Add configuration.
  • Click on “Node.js: Attach”
  • Change port to 2000 as we are running our file on 2000 port so we need to listen to 2000 port.
  • Add “restart:true” also like below and give name also.
  • After hitting save option of Testing debugging will be showing on top left corner dropdown.
  • CMD+p type
>attach
  • Hit it ,you need “Auto-attach : on” only oncs ,you can check this on down right corner.
  • Now select play button of Testing debugging on top left corner

Here is a dummy code of hello.js a simple node.js server

const express = require('express')const app = express()let request = require('request');app.get('/checkapi', async (req, res) => {request({url: 'https://jsonplaceholder.typicode.com/todos/1',headers: {'Content-Type': 'application/json'},method: 'GET',json:true}, function (err, httpResponse, data) {if (err) {res.status(400).send({ "data": err })} else {res.status(200).send({ "data": data })}});});var server = require('http').createServer(app);server.listen(process.env.PORT || 8080);console.log('server running...at 8080');

Mark debug points

Hit with postman GET http://localhost:8080/checkapi

And here we go…..

Hover over variable to see values…

Use Play button to jump to next debug point and debug line by line with next right button of it

You can also use DEBUG console at bottom and try out various js function with raw data.

you can use watch with custom expression also

Toggle within different breakpoints from BREAKPOINTS, or clear them.

If you have used external terminal to run node server you can view same logs in debug console.

For microservice architecture or you need to jump to multiple repo you can start different service on different port 2000,2001..etc and make launch configuration according to them and debug.

You can use nodemon also that hit save debugger will attach automatically because we gave “restart:true”

For Debugging Cluster node multi process you will have to take Method 2:Inspect-brk (heavy but more advanced debugging)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade