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

Callbacks in Node.js

A callback is a function passed as an argument to another function. It can be executed after a task is completed. Callbacks are commonly used in JavaScript to handle asynchronous operations.


1. What is a Callback?

A callback is simply a function that we pass to another function. The receiving function can call it when required.

Simple Trick: A callback means giving one function to another function so that the second function can call it.
Callback Flow Diagram
1. Main Function
Receives a callback function
↓
2. Task Executes
The function performs its work
↓
3. Callback Executes
Displays or processes the result

2. Simple Callback Example

In this example, the greet() function receives another function as its callback.

JavaScript
function greet(name, callback) {
    console.log("Hello " + name);
    callback();
}

function showMessage() {
    console.log("Welcome to CIIT Training Institute!");
}

greet("Samadhan", showMessage);
Output
Hello Samadhan
Welcome to CIIT Training Institute!
Explanation
  • greet() accepts a name and a callback function.
  • showMessage is passed without parentheses because we are passing the function itself.
  • Inside greet(), callback() executes the passed function.
  • The message is displayed after the greeting.

3. Callback with Data

A callback can also receive data from another function. Let's use an example involving Samadhan and Pradnya.

JavaScript
function calculateMarks(marks, callback) {
    let total = marks.reduce((sum, mark) => sum + mark, 0);
    callback(total);
}

function displayResult(total) {
    console.log("Samadhan's Total Marks: " + total);
}

calculateMarks([80, 85, 90], displayResult);
Output
Samadhan's Total Marks: 255

Here, calculateMarks() calculates the total and passes the result to displayResult() through the callback.

4. Asynchronous Callback

A callback can be used with asynchronous operations. For example, setTimeout() executes a callback after a delay.

JavaScript
console.log("Samadhan started learning");

setTimeout(function () {
    console.log("Pradnya completed the task");
}, 2000);

console.log("Samadhan continues studying");
Output
Samadhan started learning
Samadhan continues studying
Pradnya completed the task
The final message appears after approximately 2 seconds.
Asynchronous Callback Flow
Start Program
↓
Schedule setTimeout()
Callback is scheduled for later
↓
Continue Other Code
Next console.log executes
↓
Callback Executes Later
After the timer expires and the event loop can run it

5. Types of Callback Usage

Type Description Example
Synchronous Callback Executed during the current function call. array.map()
Asynchronous Callback Executed later when an asynchronous task is ready. setTimeout()
Callback with Data Receives a result as an argument. callback(total)

6. What is Callback Hell?

Callback hell happens when many callbacks are nested inside one another. The code becomes difficult to read, debug, and maintain.

JavaScript
setTimeout(() => {
    console.log("Step 1");

    setTimeout(() => {
        console.log("Step 2");

        setTimeout(() => {
            console.log("Step 3");
        }, 1000);

    }, 1000);

}, 1000);
Remember: Deeply nested callbacks can make code harder to maintain. JavaScript Promises and async/await provide alternative ways to structure many asynchronous workflows.

7. Important Points to Remember

  • A callback is a function passed to another function.
  • Use callback() to invoke the callback.
  • Callbacks can receive values as arguments.
  • Callbacks may be synchronous or asynchronous.
  • setTimeout() accepts a callback function.
  • Promises and async/await can help organize asynchronous code.

Summary

In this lesson, we learned about callbacks, passing functions as arguments, returning data through callbacks, asynchronous callbacks using setTimeout(), and callback hell. The examples featuring Samadhan, Pradnya, and CIIT Training Institute help explain how callbacks work in practical JavaScript programs.