Tutorialsteacher

Follow Us

Debug Node.js Application

In this section, you will learn ways to debug Node.js application.

You can debug Node.js application using various tools including following:

  1. Core Node.js debugger
  2. Node Inspector
  3. Built-in debugger in IDEs

Core Node.js Debugger

Node.js provides built-in non-graphic debugging tool that can be used on all platforms. It provides different commands for debugging Node.js application.

Consider the following simple Node.js application contained in app.js file.

app.js
var fs = require('fs');

fs.readFile('test.txt', 'utf8', function (err, data) {
    
    debugger;

    if (err) throw err;
    
    console.log(data);
});

Write debugger in your JavaScript code where you want debugger to stop. For example, we want to check the "data" parameter in the above example. So, write debugger; inside callback function as above.

Now, to debug the above application, run the following command.

node debug app.js

The above command starts the debugger and stops at the first line as shown below.

Starting Node.js Debugging

As you can see in the above figure, > symbol indicates the current debugging statement.

Use next to move on the next statement.

Debug Node.js Application

In the above figure, next command will set the debugger on the next line. The > is now pointing to next statement.

Use cont to stop the execution at next "debugger", if any.

Debug Node.js Application

In the above figure, you can see that cont command stops at the "debugger".

Use watch('expression') command to add the variable or expression whose value you want to check. For example, to check the value of data variable in the above example, add data into watch expression as shown below.

Debug Node.js Application

Now, write watchers command to check the value of all the variables added into watch().

Debug Node.js Application

The following table lists important debugging commands:

CommandDescription
nextStop at the next statement.
contContinue execute and stop at the debugger statement if any.
stepStep in function.
outStep out of function.
watchAdd the expression or variable into watch.
watcherSee the value of all expressions and variables added into watch.
PausePause running code.

Thus, you can use built-in Node.js debugger to debug your Node.js application. Visit Node.js official documentation to know all the Node.js debugging commands or write "help" in debug mode in the Node.js console (REPL).

Learn how to use Node Inspector to debug Node.js application in the next section.