Debugging Node.js with Google Chrome
In?software development, debugging is used when a developer locates a?code?error in a particular program and is able to reproduce it. This post describes how to debug node applications using the latest Google Chrome DevTools.
Inserting?console.log()?to code is possibly one of the most common practices for developers. However, we stop to use the console.log() in our code. We can debug into each line of the function instead of specific points with the help of Chrome DevTools. It provides us few important functionalities that?console.log()?isn’t able to provide.?
In earlier versions of Chrome, we need to manually enable the debugging features of node but with Chrome 54+ it enables as the default?
First, we need to install the current version of the node and write a program to debug it in Chrome DevTools. We can use our favorite editor to write the code, I am using Visual Studio Code.
Here I create one file called app.js under the node_debug_example folder:
let items = [111, 124, 258, 244, 207]
let totalItems = 0;
for (let i = 0; i <= items.length; i++) {
? totalItems += orders[i];
console.log(totalItems);
};
After that open the terminal in Visual Studio Code and run the below command :?
$ node --inspect-brk ?app.js
In node 6, we have to use --inspect --debug-brk for this inspect.
When –inspect is stared, a node.js process listens for a debugging client. It will listen at host and port would be like?127.0.0.1:9229.
Node services also start listing debugging messages if they have a SIGUSR1 signal. In node 7 and earlier, the SIGUSR1 signal activates the legacy debugger API. In the latest node versions (node.js 8), it activates the Inspector API.
It is not safe if the debugger is bound to a public IP address, or to 0.0.0.0, anyone who can reach your IP address will be able to connect to the debugger without any restriction and will be able to run random code.
node --inspect?binds to 127.0.0.1 by default. We need to provide a public IP address or 0.0.0.0, etc. if we propose to allow external connections to the debugger. Inspector allows local applications to access it.
‘$ node --inspect-brk ?app.js’ command display the host address, port, and UDDI for connection as below :?
领英推è
Windows PowerShel
Copyright (C) 2009 Microsoft Corporation. All rights reserved.
PS F:\node_debugg_example> node --inspect-brk? app.js
Debugger listening on ws://127.0.0.1:9229/140b121d-ed13-432a-9dcb-8112b8c62cf9
For help, see: https://nodejs.org/en/docs/inspectorl
Next, we need to open chrome and paste the below URL:
chrome://inspect/#devices
It will display the screen like:
Node fetches the inspect which is executed from the above command and it is displayed here, on click to inspect it allow us to debug our application.