Chapter 14. Testing and Debugging Node Applications

In previous chapters, the only debugging aid used in the examples was printing information to the console. For smaller and less complex applications that are still in development, this is sufficient. However, as your application grows and gets more complicated, you’ll need to use other, more sophisticated tools for debugging.

You’re also going to want to incorporate more formal testing, including the use of test-creation tools that can be used by others to test your module or application in their environments.

Debugging

Frankly, console.log will always remain my debugger of choice, but its usefulness does degrade as your application increases in size and complexity. Once you’ve moved beyond a simple application, you’re going to want to consider using more sophisticated debugging tools. We’ll go over some options in the sections that follow.

The Node.js Debugger

The V8 engine comes with a built-in debugger we can use with our Node applications, and Node provides a client that makes it simple to use. We start by adding debugger statements into our code anywhere we want a breakpoint:

// create the proxy that listens for all requests
httpProxy.createServer(function(req,res,proxy) {

   debugger;
   if (req.url.match(/^\/node\//))
      proxy.proxyRequest(req, res, {
        host: 'localhost',
        port: 8000
      });
   else
      proxy.proxyRequest(req,res, {
        host: 'localhost',
        port: 8124
      });
}).listen(9000);

We then run the application in debug mode:

node debug debugger.js ...

Get Learning Node now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.