Thursday 1 August 2019

How to debug node.js Application?


In this post, I am going to show you how to debug a node.js application using chrome development tools.

Create a node.js application like below.

HelloWorld.js
//Load express module
const express = require('express');

//Put new Express application inside app variable
const app = express();

const port = 8080;

//When user hits the home page, then the message prints in browser.
app.get('/', (req, res) => res.send('Welcome to Node.js Programming'))

app.get('/time', (req, res) => res.send(new Date().toString()))

app.get('/welcome', (req, res) => {
 var userName = req.query.name
 res.send("Hello Mr."+ userName)
})

app.get('/welcome/:userName', (req, res) => {
 res.send("Hello Mr."+ req.params.userName)
})

// Start the express application on port 8080 and print server start message to console.
app.listen(port, () => console.log(`Application started listening on port ${port}!`));

Open terminal (or) command prompt and execute HelloWorld.js application using –inspect option.


node --inspect HelloWorld.js

$>node --inspect HelloWorld.js
Debugger listening on ws://127.0.0.1:9229/9f2a616d-fab0-4f99-8216-f59106bce5b9
For help, see: https://nodejs.org/en/docs/inspector
Application started listening on port 8080!
Debugger attached.

You can see a message like above. As you see debugger is listening on port 9229.

Open browser and hit below url. Observe the url, I added the port 9229, it is because, debugger listening on port 9229.


When I hit above url in browser, I seen below messages.

[ {
  "description": "node.js instance",
  "devtoolsFrontendUrl": "chrome-devtools://devtools/bundled/js_app.html?experiments=true&v8only=true&ws=localhost:9229/9f2a616d-fab0-4f99-8216-f59106bce5b9",
  "devtoolsFrontendUrlCompat": "chrome-devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=localhost:9229/9f2a616d-fab0-4f99-8216-f59106bce5b9",
  "faviconUrl": "https://nodejs.org/static/favicon.ico",
  "id": "9f2a616d-fab0-4f99-8216-f59106bce5b9",
  "title": "HelloWorld.js",
  "type": "node",
  "url": "file://C:_Users_Public_nodeExamples_HelloWorld.js",
  "webSocketDebuggerUrl": "ws://localhost:9229/9f2a616d-fab0-4f99-8216-f59106bce5b9"
} ]

Take the devtool front end url ‘chrome-devtools://devtools/bundled/js_app.html?experiments=true&v8only=true&ws=localhost:9229/9f2a616d-fab0-4f99-8216-f59106bce5b9

‘ and open in chrome browser.

It opens above window. Click on the sources tab, to see the node.js application source.


You can add the debug points and debug the application. For example, I added debug points at lines 16 and 20.



Previous                                                    Next                                                    Home

No comments:

Post a Comment