BUILD BETTER SOFTWARE

One Simple Tip on How to Debug Your Node.js App

Learn how to debug your Node.js project using Visual Studio Code

by Vijay Athuluri

Recently, I started working on a Node.js project. If you work mostly on .NET projects and enjoy using Visual Studio IDE, then I think you'll find this quick tip for debugging your Node.js app really helpful.

First, you'll need to set up your node development environment, but don't worry, this is a quick and easy step. You can also install different packages from npm, the package manager for JavaScript.

To get started, all you need to do is download and install Node.js from here. Next, open your command prompt and type node -v, then hit enter.

Once the command runs successfully and returns the version number, your machine is ready for Node.js app development. From here, enter command node server into your app directory.

Now, you're able to open any text editor, browse your app directory, and edit your code. One of the editors I use is Sublime Text.

One of the most frequently used approaches for finding issues in Node.js applications is the heavy use of console.log for debugging. This approach can be manageable in the beginning, but once the app starts growing and you’re frequently developing new features, you'll end up with a bunch of console logs in the code, and find yourself constantly toggling back and forth between your text editor and the console panel. This can make the log file feel out of control, and finding where errors occurred can become challenging. Plus, if the app throws any errors - it will quit running. Luckily, Visual Studio Code has built-in debugging support for the Node.js runtime, and can debug JavaScript (it's a great time saver).  

Running a node app with VSCode is fairly simple. Once you've installed the VSCode, browse and open your app files with VSCode.

Once your app files are loaded, you're ready to launch your app. On the left-hand menu, you will see a small icon called "debug". When you click on the debug menu, you will be presented with a screen like this:

Click the green "play" icon. IDE will start looking for a launch config, which will have the environment settings. If there is no launch config, you will be prompted to select one from a context menu. 

Your development environment is now ready. IDE will create a launch config, which looks like the image below, and launch your app.

Once your app is running, you can debug the code right from the editor. Just open the console panel in IDE, and watch all your console logs without leaving the editor.

Then, you can debug the code using breakpoints and the call stacks will be displayed right in the IDE. 

Vijay Athuluri
Vijay Athuluri
Senior Consultant
Contact Vijay