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

Express.js Introduction

Express.js is a lightweight and flexible web framework for Node.js. It helps developers create web applications and APIs easily by providing features for routing, request handling, middleware, and response management.

In the previous module, we learned how to create an HTTP server using Node.js's built-in HTTP module. Now, we will learn how Express.js makes server-side development simpler and more organized.


1. What Is Express.js?

Express.js is a web framework that runs on Node.js. It provides a simple way to handle HTTP requests, define routes, send responses, and build REST APIs.

For example, Samadhan wants to create a website where users can view courses offered by CIIT Training Institute. Using Express.js, he can create routes for displaying course information, handling user requests, and returning responses.

Without a framework, we can use Node.js's built-in HTTP module to handle requests manually. Express.js provides convenient methods that make many common tasks easier.

JavaScript
const express = require('express');

const app = express();

app.get('/', (req, res) => {
    res.send('Welcome to Express.js!');
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

In this example, we create an Express application, define a route for the home page, send a response, and start the server on port 3000.

2. Why Do We Use Express.js?

Express.js simplifies common server-side programming tasks. It helps developers organize application logic and build APIs without manually implementing every request-handling operation.

Feature Explanation
Routing Defines how the application responds to different URLs and HTTP methods.
Request Handling Provides access to request information through the request object.
Response Handling Provides convenient methods to send text, JSON, and other responses.
Middleware Allows functions to process requests and responses in a sequence.
REST APIs Helps developers create endpoints for exchanging application data.
Static Files Supports serving files such as CSS, JavaScript, and images.

3. Node.js vs Express.js

Node.js and Express.js are related, but they are not the same thing. Node.js provides the JavaScript runtime and built-in modules. Express.js is a framework that runs on Node.js.

Node.js Express.js
A JavaScript runtime environment. A web framework for Node.js.
Provides built-in modules such as http. Provides convenient routing and request-handling methods.
Can create an HTTP server directly. Can create a web application using Express methods.
Can handle requests using lower-level APIs. Simplifies many common web development tasks.

Remember: Express.js does not replace Node.js. Express.js runs on top of Node.js and uses its capabilities.

4. Architecture of Express.js

The following diagram shows how a browser communicates with an Express.js application running on Node.js.

Client / Browser

Sends an HTTP request

↓
Express.js Application

Receives and processes the request

↓
Route Handler

Executes the matching route logic

↓
HTTP Response

Sends the result back to the client

For example, when a user opens the home page, Express.js matches the GET route for / and executes its callback function. The response is then sent to the browser.

5. Important Features of Express.js

A. Routing

Routing determines how the application responds when a client requests a particular URL using a particular HTTP method.

JavaScript
app.get('/', (req, res) => {
    res.send('Home Page');
});

app.get('/about', (req, res) => {
    res.send('About Page');
});

Here, the first route responds to requests for /, while the second responds to requests for /about.

B. Request and Response Handling

Express.js provides the req object to access information about an incoming request and the res object to send a response.

JavaScript
app.get('/student', (req, res) => {
    res.send('Student Details');
});

When the client requests /student, the server responds with the text Student Details.

C. JSON Responses

Express.js provides res.json() to send JavaScript objects or arrays as JSON responses.

JavaScript
app.get('/api/course', (req, res) => {
    res.json({
        name: 'Node.js',
        institute: 'CIIT Training Institute'
    });
});

The client receives the course information in JSON format. This is useful when developing REST APIs.

6. Creating Your First Express Application

Now let us create a simple Express.js application that responds to requests for the home page and the about page.

Step 1: Create a project folder.

Terminal
mkdir express-demo
cd express-demo

Step 2: Initialize the Node.js project.

Terminal
npm init -y

This command creates a package.json file containing project information and configuration.

Step 3: Install Express.js.

Terminal
npm install express

This command installs Express.js as a dependency of the project.

Step 4: Create a file named server.js.

server.js
const express = require('express');

const app = express();

app.get('/', (req, res) => {
    res.send('Welcome to Express.js!');
});

app.get('/about', (req, res) => {
    res.send('This is the About page.');
});

const PORT = 3000;

app.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
});

In this example, we define two GET routes. The home route responds with a welcome message, and the about route responds with information about the page.

7. Express Application Request Flow

This diagram shows how the two routes in our application respond to different browser requests.

Browser Request

GET / or GET /about

↓
Express Route Matching

Checks the HTTP method and URL

GET /

Home route

Welcome to Express.js!
GET /about

About route

This is the About page.

Express.js executes the callback associated with the matching route and sends the response to the client.

8. Running the Express Application

Save your code in server.js and execute the following command in the terminal.

Terminal
node server.js

Expected terminal output:

Terminal Output
Server running at http://localhost:3000

Test the home page:

Browser URL
http://localhost:3000/

Browser response:

Output
Welcome to Express.js!

Test the about page:

Browser URL
http://localhost:3000/about

Browser response:

Output
This is the About page.

9. Understanding the Express Code

Code Explanation
require('express') Imports the installed Express.js package.
express() Creates an Express application.
app.get() Defines a route that handles GET requests.
req Represents the incoming HTTP request.
res Represents the HTTP response.
res.send() Sends a response to the client.
res.json() Sends a JSON response.
app.listen() Starts the application server on the specified port.

10. Important Points to Remember

  • Express.js is a web framework built for Node.js.
  • Express.js must be installed before it can be imported into a project.
  • express() creates an Express application.
  • app.get() handles GET requests for specified routes.
  • req provides information about the incoming request.
  • res.send() sends a response to the client.
  • res.json() sends data as a JSON response.
  • app.listen() starts the server.
  • Express.js simplifies routing and common web application tasks.

11. Practice Tasks

Task 1: Create a Home Page

  1. Create a Node.js project.
  2. Install Express.js using npm install express.
  3. Create a file named server.js.
  4. Define a GET route for /.
  5. Display a welcome message using res.send().

Expected result: Opening the home page should display a welcome message in the browser.

Task 2: Create an About Page

  1. Create a GET route for /about.
  2. Return a message describing your application.
  3. Start the server and test the route in your browser.

Expected result: The about page should display the message returned by the Express route.

Task 3: Return Course Information

  1. Create a GET route named /api/course.
  2. Create an object containing a course name and institute name.
  3. Return the object using res.json().
  4. Open the route in the browser to view the JSON response.

Expected result: The browser should display course information in JSON format.

Summary

In this lesson, we learned that Express.js is a web framework for Node.js that simplifies routing, request handling, and response management. We compared Node.js with Express.js, explored its architecture, and created our first Express application with home and about routes.

Remember the flow: Client Request → Express Application → Route Handler → HTTP Response.