Debugging NodeJS Apps Made Easy with ndb

Debugging is an inevitable part of development, but the default process for debugging NodeJS applications can be clunky and awkward. Thankfully, there‘s a better way—ndb.

Ndb is an improved debugging experience for NodeJS, enabled by Chrome DevTools. With ndb, you can easily debug NodeJS apps without the hassle of using –inspect, configuring WebSockets, or being tied to Chrome. It provides an integrated debugging environment that saves you time and effort.

In this guide, I‘ll walk you through getting started with ndb for debugging NodeJS applications. Whether you‘re an ndb newbie or transitioning from the legacy NodeJS debugger, you‘ll learn everything you need to know to debug like a pro. Let‘s dive in!

What is ndb?

Ndb is an open-source tool from Google Chomelab that provides an enhanced debugging experience for NodeJS. Out of the box, it offers powerful debugging features:

  • Automatic debugging of NodeJS processes, no code changes required
  • One-click breakpoint setting
  • Instant code reloading
  • Inspection tools for variables, functions, call stack, etc.
  • Debugging for tests and npm scripts

The best part is ndb works universally across Windows, macOS and Linux. It uses familiar Chrome DevTools to provide a clean GUI, while still being compatible with text editors and IDEs. No more juggling terminal windows!

Why ndb over node-inspector and built-in debugging?

You may be wondering why to use ndb over node-inspector or the legacy built-in NodeJS debugger. Here are some key advantages of ndb:

  • No setup required – ndb works out of the box, no code changes needed
  • Browser-agnostic – ndb isn‘t coupled to Chrome or any specific browser
  • Automatic source maps – ndb automatically resolves source maps for you
  • Intelligent auto-attach – ndb automatically attaches to child processes
  • Advanced debugging – ndb offers function breakpoints, blackboxing, logpoints, etc.

Using ndb provides a modern, streamlined debugging workflow that eliminates context-switching and boosts productivity. You‘ll be able to debug NodeJS code with minimal friction.

Setting up ndb

Before we start debugging, let‘s get ndb installed on your machine. Ndb requires NodeJS version 8 or higher. You can install it globally using npm:

npm install -g ndb

Or if you prefer yarn:

yarn global add ndb  

To verify the installation, run:

ndb -v

You should see the current version of ndb printed. That‘s it – you‘re ready to start debugging!

Debugging a NodeJS application with ndb

Now let‘s walk through debugging a real-world NodeJS application using ndb. We‘ll use a sample Express API for currency conversion. The app fetches exchange rates from a database if available, otherwise from an external API, and returns the converted amount.

Step 1: Clone the sample application

First, clone the currency conversion API repo:

git clone https://github.com/yourusername/currency-api.git
cd currency-api

Install the dependencies:

npm install

The main logic resides in src/exchangeRates.js. The app also includes some unit tests we can use to demonstrate debugging tests.

Step 2: Run the application with ndb

With the default NodeJS debugger, you‘d have to run the app with –inspect and configure the WebSocket connection. With ndb, simply run:

ndb npm start

This runs the "start" script defined in package.json, which in turn runs the app using nodemon. Ndb automatically attaches to the NodeJS process, no setup required!

Ndb will open an instance of Chrome DevTools as shown below:

ndb Chrome DevTools

Step 3: Set a breakpoint

Let‘s set a breakpoint to pause execution at a specific line of code. Open src/exchangeRates.js and click the gutter (line number area) at line 45 to set a breakpoint:

Setting breakpoint in ndb

Now open your browser and hit the API endpoint to trigger the code path:

http://localhost:8080/api/convert/USD/AUD/2019-01-01

Execution will pause at the breakpoint and you can start debugging!

Step 4: Step through the code

Once paused at a breakpoint, you can use the DevTools controls to step through the code:

  • Resume (F8): Resumes execution until the next breakpoint/end
  • Step Over (F10): Steps over the current line
  • Step Into (F11): Steps into the current function
  • Step Out: (Shift+F11): Steps out of the current function
  • Deactivate breakpoints: Temporarily disables all breakpoints

Use these controls to step through exchangeRates.js and examine the program state at each pause.

Step 5: Inspect variables and scope

While paused, you can hover over any variable to view its current value. The Scope pane also shows in-scope variables and their values for the current execution context:

Scope variables in ndb DevTools

Expand objects and arrays inline to explore their properties. You can even modify values during runtime!

Step 6: Watch variables

To monitor variable values over time, use watches. Right-click a variable and select "Add to watch":

Add watch in ndb DevTools

The variable will appear in the Watch pane and its value will update as you step through the code. You can also enter custom watch expressions here.

Step 7: View the call stack trace

The Call Stack pane displays the current execution context and call stack. Use this to understand the sequence of function calls that led to the current line of code:

Call stack in ndb DevTools

Clicking a stack frame jumps to the relevant source code location. The call stack is vital for tracing the flow of asynchronous code.

Debugging tests and npm scripts with ndb

Beyond debugging a running NodeJS app, you can also use ndb to debug tests and npm scripts. To debug a test file:

ndb npm test

Or to debug any npm script:

ndb npm run script-name  

Ndb automatically attaches to the relevant NodeJS process, allowing you to debug just like you would production code. This is incredibly useful for tracing bugs within your unit tests.

Additional ndb features

Ndb offers some handy bonus features to streamline your debugging experience:

  • Auto-attaches to child processes, ideal for microservices
  • Resolves source maps, making it easy to debug transpiled/minified code
  • Integrates with any text editor/IDE for seamless debugging
  • Supports remote debugging for Docker containers, VMs, etc.
  • Includes an interactive REPL for executing code in the debug context

Try experimenting with these features as you incorporate ndb into your regular debugging workflow. Ndb can handle pretty much any NodeJS debugging scenario you throw at it!

Best practices for debugging with ndb

To get the most out of ndb, keep these best practices in mind:

  • Launch the debugger early and often, don‘t wait until you have a bug
  • Set breakpoints liberally, including in dependencies and Node internals
  • Use conditional breakpoints for hard-to-reach code paths
  • Step through unfamiliar code flows to understand them
  • Watch all key variables and objects and monitor their values
  • Keep an eye on the call stack to understand async flow
  • Debug both production code and tests, not just one or the other

Effective debugging is a skill that takes practice. The more you use ndb and explore its features, the more productive you‘ll become at diagnosing and resolving NodeJS bugs.

Conclusion

If you‘ve been struggling with the awkwardness of –inspect and the legacy NodeJS debugger, ndb is a breath of fresh air. With its user-friendly Chrome DevTools GUI, smart defaults, and advanced features, ndb empowers you to debug NodeJS applications with minimal setup and friction.

To get started with ndb, simply install it globally with npm/yarn, then run your app, tests, or npm scripts using the ndb command. Set breakpoints, step through code, and inspect variables just like you would with client-side JavaScript. Ndb has you covered across the entire spectrum of NodeJS development, from tiny scripts to complex microservices.

While mastering debugging takes time and practice, tools like ndb make the process far more approachable. The minutes you spend learning ndb will pay dividends in hours of productive debugging. Try incorporating ndb into your NodeJS debugging workflow—I promise you won‘t regret it!

Similar Posts