0
0
NodejsDebug / FixBeginner · 4 min read

How to Debug Node.js Application: Simple Steps and Tips

To debug a Node.js application, use the built-in --inspect flag to start your app with debugging enabled and connect it to Chrome DevTools or VS Code. You can also use console.log for simple checks, but --inspect provides step-by-step debugging and breakpoints.
🔍

Why This Happens

When you run a Node.js app normally, it executes all code without pausing, so you can't see what happens inside step-by-step. This makes it hard to find where errors or unexpected behavior occur.

For example, if you want to check a variable's value at a certain point, just running the app won't help because it doesn't stop or show internal states.

javascript
function add(a, b) {
  return a + b;
}

const result = add(5, '3');
console.log('Result:', result);
Output
Result: 53
🔧

The Fix

Start your Node.js app with the --inspect flag to enable debugging. Then open Chrome and go to chrome://inspect to connect and set breakpoints. This lets you pause execution, inspect variables, and step through code.

Alternatively, use VS Code's debugger by creating a launch configuration that runs your app with debugging enabled.

javascript
function add(a, b) {
  debugger; // This will pause execution here
  return a + b;
}

const result = add(5, 3);
console.log('Result:', result);
Output
Result: 8
🛡️

Prevention

To avoid debugging headaches, write clear code and use console.log for quick checks. Use linting tools like ESLint to catch errors early. Always run your app with --inspect during development to catch issues early with breakpoints and step-through debugging.

Keep your Node.js and debugging tools updated for best support.

⚠️

Related Errors

Common related issues include:

  • Syntax errors: Use linters and editors to catch these before running.
  • Unhandled promise rejections: Use try/catch with async/await and process.on('unhandledRejection', handler) to catch them.
  • Memory leaks: Use profiling tools in Chrome DevTools to find leaks.

Key Takeaways

Use node --inspect to enable powerful debugging with breakpoints.
Connect Chrome DevTools or VS Code debugger to step through your code.
Use console.log for quick checks but prefer step debugging for complex issues.
Keep your code clean and use linters to catch errors early.
Handle promises properly to avoid unhandled rejections during debugging.