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 HTTP Server in Node.js

Node.js allows us to create an HTTP server using its built-in http module. The server listens for client requests, processes them, and sends responses back to the client.


1. What is an HTTP Server?

An HTTP server receives HTTP requests from clients such as web browsers and sends HTTP responses. In Node.js, we can create a basic server using http.createServer().

Imagine Samadhan opens the CIIT Training Institute website. His browser sends a request to the server. The server processes the request and returns a response that the browser can display.

Simple Trick: The server listens, receives a request, processes it, and sends a response.

2. Import the HTTP Module

First, import the built-in http module. We do not need to install an additional npm package for it.

JavaScript
const http = require("http");

console.log("HTTP module imported successfully.");
Output
HTTP module imported successfully.
Explanation
  • require("http") loads the Node.js HTTP module.
  • The imported module is stored in the http variable.
  • We use this object to create an HTTP server.

3. Creating a Basic HTTP Server

The http.createServer() method creates an HTTP server. Its callback receives two objects: req and res.

JavaScript
const http = require("http");

const server = http.createServer((req, res) => {
    res.end("Welcome to CIIT Training Institute!");
});

server.listen(3000, () => {
    console.log("Server running at http://localhost:3000");
});
Terminal Output
Server running at http://localhost:3000
Browser Output
Welcome to CIIT Training Institute!
Explanation
  1. http.createServer() creates the server.
  2. req represents the incoming request.
  3. res represents the outgoing response.
  4. res.end() sends the response body and completes the response.
  5. server.listen(3000) starts listening on port 3000.

4. HTTP Server Request–Response Flow

Server Communication Diagram
Client / Browser
Samadhan opens the website.
↓
HTTP Request
GET /
↓
Node.js HTTP Server
Processes the request callback.
↓
HTTP Response
Welcome to CIIT Training Institute!
↓
Browser Displays Response

5. Setting Status Code and Headers

We can use res.writeHead() to set the HTTP status code and response headers. For example, status code 200 indicates success.

JavaScript
const http = require("http");

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

    res.end("Hello Samadhan! Your server is working.");
});

server.listen(3000, () => {
    console.log("Server started on port 3000");
});
Browser Output
Hello Samadhan! Your server is working.
Explanation
  • 200 is the HTTP success status code.
  • Content-Type tells the client how to interpret the response body.
  • text/plain indicates that the response contains plain text.
  • res.end() completes the response.

6. Sending an HTML Response

An HTTP server can also return HTML. Set the content type to text/html so the browser interprets the response as HTML.

JavaScript
const http = require("http");

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

    res.end(`
        <h1>CIIT Training Institute</h1>
        <p>Welcome, Pradnya!</p>
    `);
});

server.listen(3000, () => {
    console.log("Server running on port 3000");
});
Browser Output

CIIT Training Institute

Welcome, Pradnya!

Important: Stop the previously running server before starting another example on the same port. Otherwise, Node.js may report that the port is already in use.

7. HTTP Server Lifecycle

Server Lifecycle Diagram
1. Import HTTP Module
↓
2. Create Server
Register the request handler.
↓
3. Listen on a Port
Wait for incoming requests.
↓
4. Process Client Request
Use the request and response objects.
↓
5. Send Response
Return the result to the client.

8. How to Run the Server

  1. Create a JavaScript file named server.js.
  2. Paste one of the server examples into the file.
  3. Open a terminal in the same directory.
  4. Run the following command.
Terminal
node server.js

Open this address in your browser:

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

9. Understanding Request and Response Objects

Object / Method Purpose
req Contains information about the incoming request.
res Used to construct and send the response.
http.createServer() Creates an HTTP server.
server.listen() Starts listening for client connections.
res.writeHead() Sets the status code and response headers.
res.write() Writes part of the response body.
res.end() Completes the response.

10. Common Mistakes

Mistake Correct Approach
Forgetting server.listen(). Start listening on an available port.
Forgetting res.end(). Complete the response when all response data has been sent.
Using the wrong content type. Choose a content type that matches the response, such as text/plain or text/html.
Starting multiple servers on the same port. Stop the old server or select another available port.
Confusing terminal output with browser output. Use console.log() for terminal messages and res.end() for the HTTP response.

11. Important Points to Remember

  • The HTTP module is built into Node.js.
  • http.createServer() creates the server.
  • The request handler receives req and res.
  • server.listen() starts listening on a port.
  • res.writeHead() sets the response status and headers.
  • res.end() completes the response.
  • The browser can display plain text, HTML, or other supported response formats.

Summary

In this lesson, we learned how to create an HTTP server in Node.js, import the HTTP module, handle incoming requests, send text and HTML responses, set status codes and headers, and start a server using server.listen(). Examples involving Samadhan, Pradnya, and CIIT Training Institute demonstrate the basic server workflow.