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

Creating an Express Server

An Express server is a web server application built using Express.js on Node.js. It receives HTTP requests from clients, processes them using routes, and sends responses back to the clients.

In this lesson, we will learn how to create an Express application, define routes, start a server using app.listen(), and test the server in a browser.


1. What Is an Express Server?

An Express server is an application that uses the Express.js framework to handle HTTP requests and responses. It runs on Node.js and can provide web pages, JSON data, and API endpoints.

For example, Samadhan wants to create a server for CIIT Training Institute. When a user opens the home page, the server returns a welcome message.

JavaScript
const express = require('express');

const app = express();

app.get('/', (req, res) => {
    res.send('Welcome to CIIT Training Institute!');
});

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

This code creates an Express application, defines a home page route, and starts the server on port 3000.

2. Requirements for Creating an Express Server

Before creating an Express server, make sure Node.js and Express.js are available in your project.

Requirement Purpose
Node.js Runs the JavaScript application.
Express.js Provides routing and convenient request and response handling.
server.js Contains the server application code.
Port Allows the server to listen for connections on a specified port.

If Express.js has not yet been installed, run the following command inside the project folder.

Terminal
npm install express

3. Creating an Express Application

First, import the Express package and create an application using express().

JavaScript
const express = require('express');

const app = express();

Explanation:

  • require('express') imports the Express.js package.
  • express() creates an Express application.
  • app is used to configure routes and start the server.

The application object is the main object we use to define the behavior of our Express server.

4. Defining a Route

A route determines how the application responds to a request for a particular URL and HTTP method.

Example:

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

Explanation:

Code Meaning
app.get() Defines a route for GET requests.
'/' Represents the root or home route.
req Represents the incoming HTTP request.
res Represents the HTTP response.
res.send() Sends a response to the client.

5. Express Server Architecture

The following diagram explains how a browser communicates with an Express server.

Client / Browser

Sends an HTTP request

↓
Express Application

Receives the request

↓
Route Handler

Executes the matching route

↓
HTTP Response

Returns the result to the browser

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

6. Starting the Express Server Using app.listen()

The app.listen() method starts the server so that it can accept incoming connections on a specified port.

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

Explanation:

  • 3000 is the port number.
  • The callback function runs when the server starts listening.
  • The console message confirms that the server has started.

If port 3000 is already in use, the server may fail to start. In that case, use another available port.

7. Complete Example: Creating an Express Server

Now let us combine the application, routes, and server startup into a single program.

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

const app = express();

const PORT = 3000;

// Home route
app.get('/', (req, res) => {
    res.send('Welcome to CIIT Training Institute!');
});

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

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

This application contains two routes. The home route returns a welcome message, while the about route returns information about the page.

8. Request Flow for the Complete Server

The diagram below shows how Express handles requests for the two routes in our example.

Browser Request

GET / or GET /about

↓
Express Route Matching

Checks the requested URL and method

Home Route

GET /

Welcome to CIIT Training Institute!
About Route

GET /about

This is the About page.

9. Running and Testing the Server

Save the program in server.js and run the following command from the project folder.

Terminal
node server.js

Expected terminal output:

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

Test the home route:

Browser URL
http://localhost:3000/

Browser output:

Output
Welcome to CIIT Training Institute!

Test the about route:

Browser URL
http://localhost:3000/about

Browser output:

Output
This is the About page.

10. Common Mistakes to Avoid

Mistake Explanation Solution
Express is not installed The application cannot load the Express package. Run npm install express in the project folder.
Incorrect route URL The requested URL does not match a defined route. Check the route path and the browser URL.
Port already in use Another process is using the selected port. Stop the other server or select another port.
Server not started The application is not listening for requests. Run node server.js and check terminal errors.

11. Practice Tasks

Task 1: Create a Home Route

  1. Create a file named server.js.
  2. Import Express.js and create an application.
  3. Define a GET route for /.
  4. Return a welcome message using res.send().
  5. Start the server on port 3000.

Expected result: The browser should display the welcome message when you open the home page.

Task 2: Create an About Route

  1. Add a GET route for /about.
  2. Return a message describing your application.
  3. Run the server and open the about URL.

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

Summary

In this lesson, we learned how to create an Express application, define GET routes, handle requests using callback functions, send responses with res.send(), and start the server using app.listen().

Remember the flow: Import Express → Create Application → Define Routes → Start Server → Test in Browser.