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

HTTP Module Introduction in Node.js

The Node.js HTTP module allows us to create web servers, receive HTTP requests from clients, and send HTTP responses. It is a built-in module, so we can use it without installing an external package.


1. What is the HTTP Module?

HTTP stands for Hypertext Transfer Protocol. It defines how clients and servers communicate over the web. Node.js provides the built-in http module to create HTTP servers and handle requests and responses.

Imagine Samadhan opens the CIIT Training Institute website in his browser. His browser sends an HTTP request to the server. The server processes the request and sends back an HTTP response containing information such as a web page or text message.

Simple Trick: The client asks a question through an HTTP request, and the server sends an answer through an HTTP response.

2. Why Do We Use the HTTP Module?

  • To create an HTTP server using Node.js.
  • To receive requests from browsers and other clients.
  • To inspect request URLs and HTTP methods.
  • To send responses such as text, HTML, and JSON.
  • To build simple APIs and web-server applications.

3. How Client and Server Communicate

HTTP Request and Response Flow
Client / Browser
Samadhan opens the CIIT website.
↓
HTTP Request
GET /
↓
Node.js HTTP Server
Receives and processes the request.
↓
HTTP Response
Status: 200 OK
Body: Welcome to CIIT Training Institute!
↓
Client / Browser
Receives and displays the response.

4. Importing the HTTP Module

The http module is built into Node.js. In a CommonJS JavaScript file, we can import it using require().

JavaScript
const http = require("http");

console.log("HTTP module loaded successfully.");
Output
HTTP module loaded successfully.
Explanation
  • require("http") loads the built-in HTTP module.
  • const http stores the imported module.
  • We can use the http object to create a server.
  • No separate npm package installation is required for this module.

5. Creating a Basic HTTP Server

We can create an HTTP server using http.createServer(). It accepts a callback that receives the incoming request and outgoing response objects.

JavaScript
const http = require("http");

const server = http.createServer((req, res) => {
    res.writeHead(200, {
        "Content-Type": "text/plain"
    });

    res.end("Welcome to CIIT Training Institute!");
});

server.listen(3000, () => {
    console.log("Server running at http://localhost:3000");
});
Console Output
Server running at http://localhost:3000
Browser Output
Welcome to CIIT Training Institute!
Explanation
  1. http.createServer() creates an HTTP server.
  2. req represents the incoming request.
  3. res represents the response sent by the server.
  4. res.writeHead(200, ...) sets the status code and response content type.
  5. res.end() sends the response body and completes the response.
  6. server.listen(3000) starts listening on port 3000.

6. Understanding req and res

Object Meaning Common Usage
req Incoming HTTP request. req.url, req.method, req.headers
res Outgoing HTTP response. res.writeHead(), res.write(), res.end()
Remember: The request contains information sent by the client. The response contains information sent back by the server.

7. HTTP Server Execution Flow

Server Lifecycle Diagram
1. Import HTTP Module
Load the built-in module.
↓
2. Create Server
Register the request handler.
↓
3. Listen on Port
Wait for incoming client requests.
↓
4. Handle Request
Use req to inspect incoming request information.
↓
5. Send Response
Use res to return data to the client.

8. How to Run the HTTP Server

Follow these steps to execute the example on your computer.

  1. Install Node.js if it is not already installed.
  2. Create a file named server.js.
  3. Paste the basic HTTP server code into that file.
  4. Open a terminal in the folder containing server.js.
  5. Run the following command.
Terminal
node server.js

After the server starts, open this address in your browser:

URL
http://localhost:3000
Important: Keep the terminal running while testing the server. If port 3000 is already occupied, choose another available port and update the URL.

9. Important HTTP Module Methods

Method / Property Purpose
http.createServer() Creates an HTTP server.
server.listen() Starts listening for incoming connections.
req.url Provides the request URL path and query string.
req.method Provides the HTTP method, such as GET or POST.
res.writeHead() Sets the response status code and headers.
res.write() Writes part of the response body.
res.end() Completes the response.

10. Common Mistakes

Mistake Correct Approach
Forgetting to call server.listen(). Start the server on an available port.
Forgetting to finish the response. Call res.end() when the response is complete.
Using the wrong content type. Set an appropriate header, such as text/plain for plain text.
Choosing a port that is already occupied. Use an available port or stop the conflicting process.
Expecting the browser to show the terminal message as page content. Use console.log() for terminal output and res.end() for browser response content.

11. Important Points to Remember

  • The HTTP module is built into Node.js.
  • http.createServer() creates a server.
  • req contains incoming request information.
  • res is used to send the response.
  • server.listen() starts listening on a port.
  • res.end() completes the response.
  • The built-in HTTP module can be used to create basic web servers and APIs.

Summary

In this lesson, we learned what the Node.js HTTP module is, why it is used, how clients and servers communicate, and how to create a basic HTTP server. We also explored request and response objects, important HTTP methods, server execution, and common mistakes using examples from CIIT Training Institute involving Samadhan and Pradnya.