Debugging Node.JS!

Aditya Bhamidipati
2 min readMar 4, 2021

As per Hofstadter’s Law, it always takes longer than we expect to implement any development feature. Bugs are a byproduct of code. On a lighter note, the number of lines of code is directly proportional to number of bugs. So, debugging is one of the essential skills every developer should have. The more knowledge about the local variables and flow of control, the easier it is to triage bugs and fix them.

Javascript is one of the popular languages and Node.js proved quite efficient for highly scalable, data intensive and real time apps. Learning Node.js development with novice knowledge in javascript, the first thing I learned is debugging. Here are the three techniques to debug a Node application:

Log to console:

Node.js is a runtime environment for executing javascript outside browser. So, we don’t have window or document object in this environment.Fortunately console is now part of the global object of Node.js.

global.console.log(“This is a wanderers web debug post !”)

Throw Exceptions:

Throwing Exceptions to understand data or application flow is another way to debug an application. If you are shipping logs to a different application (log file, data dog etc), exception message can be seen there otherwise it can be found on console.

Below shows an example to throw exception:

Throw Error(“This is a wanderers web debug post !”);

Debug with IDE:

Third way to debug is with breakpoints in your IDE. One of the popular IDEs for javascript is Visual Studio Code. We need to add a launch.json at the root of your Node.js application with the following configuration.

{
// 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": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}/dist/index.js",
"preLaunchTask": "tsc: build - tsconfig.json",
"outFiles": [
"${workspaceFolder}/dist/**/*.js"
]
}
]
}

Debugging is one of the most underrated skill to learn a new language. Above techniques can be used to understand existing Node.js application or implement a greenfield project.

--

--