Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

Debugging Node.js Applications

Debugging is the process of finding, analyzing, and fixing errors in an application. Node.js provides built-in debugging tools that help developers inspect variables, pause program execution, set breakpoints, and understand how code behaves at runtime.

1. What Is Debugging?

Debugging is a systematic process used to identify the cause of unexpected program behavior and correct it.

For example, if an API returns an incorrect total, debugging helps us inspect the input values, follow the program execution, and locate the calculation that produces the wrong result.

JavaScript — app.js
function calculateTotal(price, quantity) {
    return price + quantity;
}

const total = calculateTotal(100, 3);

console.log("Total:", total);

Output

Terminal
Total: 103

The intended calculation is multiplication, not addition. Debugging helps us identify the incorrect operator and fix the logic.

JavaScript — Corrected Code
function calculateTotal(price, quantity) {
    return price * quantity;
}

const total = calculateTotal(100, 3);

console.log("Total:", total);

Correct Output

Terminal
Total: 300

2. Why Is Debugging Important?

  • Helps identify the root cause of errors.
  • Allows developers to inspect variable values during execution.
  • Helps understand the order in which functions are called.
  • Reduces the time needed to troubleshoot application problems.
  • Helps identify incorrect business logic.
  • Improves code quality, reliability, and maintainability.
Remember: Error handling manages failures. Debugging investigates why a problem occurred and helps you fix its cause.

3. Common Types of Bugs

Bug Type Description Example
Syntax Bug Invalid JavaScript syntax prevents code from parsing. Missing a closing parenthesis.
Logic Bug The code runs but produces an incorrect result. Adding values instead of multiplying them.
Runtime Bug An unexpected failure occurs while the program executes. Calling a method on an undefined value.
Asynchronous Bug Incorrect handling of asynchronous operations. Using a result before a Promise resolves.
Integration Bug Different application components do not work together correctly. An API expects a different property name.

4. Debugging Using console.log()

console.log() is one of the simplest debugging techniques. It prints variable values and messages to the terminal.

JavaScript — debug.js
function calculateTotal(price, quantity) {
    console.log("Price:", price);
    console.log("Quantity:", quantity);

    const total = price * quantity;

    console.log("Calculated total:", total);

    return total;
}

const result = calculateTotal(250, 4);

console.log("Final result:", result);

Run the Program

Terminal
node debug.js

Output

Terminal
Price: 250
Quantity: 4
Calculated total: 1000
Final result: 1000

These messages help us confirm whether the function receives the expected inputs and calculates the correct result.

Best practice: Use structured logging for production applications. Avoid logging passwords, access tokens, or sensitive user data.

5. Useful Console Methods

Node.js provides several console methods that are useful while debugging.

Method Purpose
console.log() Prints general debugging information.
console.error() Writes an error message to standard error.
console.warn() Displays a warning message.
console.table() Displays tabular data in a readable format.
console.time() Starts a timer for measuring elapsed time.
console.timeEnd() Stops a matching timer and displays elapsed time.
JavaScript
const users = [
    { id: 1, name: "Amit", role: "Admin" },
    { id: 2, name: "Priya", role: "User" }
];

console.table(users);

console.warn("This is a warning message");

console.error("This is an error message");

console.time("calculation");

for (let i = 0; i < 100000; i++) {
    // Example operation
}

console.timeEnd("calculation");

The elapsed time varies by computer and runtime. Use these methods to inspect program behavior, not as a replacement for a proper profiler.

6. Debugging with the Node.js Inspector

Node.js includes a built-in inspector that allows developers to pause execution, inspect variables, step through code, and examine call stacks.

Save the following program as debug.js:

JavaScript — debug.js
function calculateTotal(price, quantity) {
    const total = price * quantity;

    debugger;

    return total;
}

const result = calculateTotal(100, 5);

console.log("Total:", result);

The debugger; statement creates a breakpoint when an active debugger is attached.

Start Debugging

Terminal
node inspect debug.js

Node.js starts its command-line debugger. You can use debugger commands to step through the program and inspect the current execution state.

Note: Debugger commands and displayed information may differ slightly between Node.js versions. The VS Code debugger is another convenient way to work with breakpoints and variables.

7. What Is a Breakpoint?

A breakpoint pauses program execution at a selected line so you can inspect values before the program continues.

JavaScript
function calculateDiscount(price, discount) {
    const discountAmount = price * discount / 100;
    const finalPrice = price - discountAmount;

    return finalPrice;
}

const result = calculateDiscount(1000, 10);

console.log("Final price:", result);

In VS Code, click next to the line containing const finalPrice = ... to set a breakpoint. Start debugging and inspect price, discount, and discountAmount.

Expected Output

Terminal
Final price: 900

Breakpoints help you:

  • Inspect local variables.
  • Follow function execution step by step.
  • Find where a value becomes incorrect.
  • Understand conditional branches and loops.

8. Debugging Node.js in Visual Studio Code

Follow these steps to debug a Node.js application in VS Code.

  1. Open your Node.js project folder in Visual Studio Code.
  2. Open the JavaScript file you want to debug.
  3. Click beside a line number to add a breakpoint.
  4. Open the Run and Debug panel.
  5. Select a Node.js debugging configuration or create one if needed.
  6. Start debugging.
  7. Inspect variables in the Variables panel.
  8. Use Step Over, Step Into, and Continue to control execution.
Debugging Action Purpose
Continue Runs until the next breakpoint or program completion.
Step Over Executes the current line without stepping into a called function.
Step Into Enters a function called by the current line.
Step Out Continues until the current function returns.
Restart Restarts the debugging session.
Stop Ends the debugging session.

9. Debugging Asynchronous Code

Asynchronous operations are common in Node.js. Debugging them requires checking Promise results, execution order, and error handling.

JavaScript
function getUser() {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve({ id: 1, name: "Amit" });
        }, 1000);
    });
}

async function main() {
    console.log("Fetching user...");

    try {
        const user = await getUser();

        console.log("User:", user);
    } catch (error) {
        console.error("Failed to fetch user:", error.message);
    }
}

main();

Output

Terminal
Fetching user...
User: { id: 1, name: 'Amit' }

To debug this program, place breakpoints before and after await getUser(). Inspect the returned object and verify whether the Promise resolves or rejects as expected.

10. Basic Performance Debugging

Sometimes the application is correct but runs slowly. Timing operations can help identify which section needs further investigation.

JavaScript
console.time("loop");

let total = 0;

for (let i = 0; i < 1000000; i++) {
    total += i;
}

console.timeEnd("loop");

console.log("Total:", total);

Output

Terminal
loop: [elapsed time varies]
Total: 499999500000

This technique measures elapsed time for a section of code. For deeper performance analysis, use Node.js profiling tools to inspect CPU usage, memory consumption, and expensive operations.

11. Debugging Workflow

Step 1: Identify the Problem

Observe incorrect output, an error, or slow execution.

↓
Step 2: Reproduce the Issue

Find the conditions that cause the problem.

↓
Step 3: Inspect the Code

Use logs, breakpoints, and variable inspection.

↓
Step 4: Fix the Root Cause

Correct the logic or handle the failure properly.

↓
Step 5: Test Again

Verify the fix and check for regressions.

12. Debugging Best Practices

  • Reproduce the issue before attempting a fix.
  • Use breakpoints to inspect variables and execution flow.
  • Use clear, meaningful log messages.
  • Check asynchronous errors and rejected Promises.
  • Test edge cases and invalid input.
  • Remove temporary debugging statements when they are no longer needed.
  • Never expose secrets or personal information in logs.
  • Use automated tests to confirm that fixes work.
  • Use profiling tools when investigating performance issues.

Important Points to Remember

  • Debugging helps identify and fix the root cause of problems.
  • console.log() is useful for inspecting values.
  • The Node.js inspector supports interactive debugging.
  • Breakpoints pause execution at selected lines.
  • VS Code provides variable inspection and step-by-step execution.
  • Asynchronous code requires careful inspection of Promise results.
  • Profiling tools help investigate performance problems.

Summary

Debugging is essential for finding and fixing problems in Node.js applications. Developers can use console methods, the built-in Node.js inspector, breakpoints, and VS Code debugging tools to inspect program execution. A systematic workflow helps locate the root cause, verify fixes, and maintain reliable applications.