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

Sending Responses in Node.js

In Node.js, an HTTP response is sent from the server back to the client. We can send plain text, HTML, JSON data, status codes, and headers using the response object provided by the built-in HTTP module.


1. What is an HTTP Response?

An HTTP response is the server's reply to a client's request. It normally contains a status code, response headers, and optionally a response body.

For example, Samadhan opens the CIIT Training Institute website. The Node.js server processes his request and sends a response that the browser can display.

Simple Trick: Request means the client asks. Response means the server answers.

2. Structure of an HTTP Response

HTTP Response Structure
1. Status Code
Example: 200 OK
↓
2. Response Headers
Example: Content-Type: text/plain
↓
3. Response Body
Example: Welcome to CIIT Training Institute!
Three Important Parts
  • Status code: Indicates the result of the request.
  • Headers: Provide metadata about the response.
  • Body: Contains the actual data sent to the client, when applicable.

3. Setting Status Codes and Headers

The res.writeHead() method sets the HTTP status code and response headers before the response is sent.

JavaScript
const http = require("http");

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

    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
  • 200 indicates that the request succeeded.
  • Content-Type tells the client how to interpret the response body.
  • text/plain identifies the body as plain text.
  • res.end() sends the body and completes the response.

4. Sending a Plain Text Response

Use the text/plain content type when the server needs to return ordinary text.

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 request was successful.");
});

server.listen(3000, () => {
    console.log("Server started on port 3000");
});
Browser Output
Hello Samadhan! Your request was successful.

The browser displays the text received in the response body.

5. Sending an HTML Response

To return HTML content, set the content type to text/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>
        <p>Learn Node.js with practical examples.</p>
    `);
});

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

CIIT Training Institute

Welcome, Pradnya!

Learn Node.js with practical examples.

Remember: The browser interprets the body as HTML because the server specifies the text/html content type.

6. Sending a JSON Response

JSON is commonly used by APIs to send structured data. Node.js provides JSON.stringify() to convert a JavaScript object into a JSON string.

JavaScript
const http = require("http");

const server = http.createServer((req, res) => {
    const student = {
        name: "Samadhan",
        course: "Node.js",
        institute: "CIIT Training Institute"
    };

    res.writeHead(200, {
        "Content-Type": "application/json; charset=utf-8"
    });

    res.end(JSON.stringify(student));
});

server.listen(3000, () => {
    console.log("Server started on port 3000");
});
Browser Output
JSON
{
  "name": "Samadhan",
  "course": "Node.js",
  "institute": "CIIT Training Institute"
}
Explanation
  • The student variable stores a JavaScript object.
  • JSON.stringify(student) converts the object into JSON text.
  • application/json identifies the response as JSON.
  • The client can parse the response as JSON data.

7. Difference Between res.write() and res.end()

The res.write() method writes part of the response body. The res.end() method completes the response and can optionally send the final body content.

JavaScript
const http = require("http");

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

    res.write("Hello Samadhan! ");
    res.write("Welcome to ");

    res.end("CIIT Training Institute.");
});

server.listen(3000, () => {
    console.log("Server started on port 3000");
});
Browser Output
Hello Samadhan! Welcome to CIIT Training Institute.
Method Purpose
res.write() Writes a chunk of the response body without completing the response.
res.end() Completes the response and optionally writes the final data.
Important: Do not try to write more response data after calling res.end(). The response has already been completed.

8. Common HTTP Status Codes

Status Code Meaning Typical Use
200 OK Request succeeded.
201 Created A new resource was created.
400 Bad Request The request contains invalid input.
404 Not Found The requested resource was not found.
500 Internal Server Error An unexpected server-side error occurred.

9. Sending a 404 Not Found Response

If the requested resource does not exist, the server should return a suitable status code such as 404 instead of returning success.

JavaScript
const http = require("http");

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

        res.end("Welcome to CIIT Training Institute!");
    } else {
        res.writeHead(404, {
            "Content-Type": "text/plain; charset=utf-8"
        });

        res.end("404 - Page Not Found");
    }
});

server.listen(3000, () => {
    console.log("Server started on port 3000");
});
Test URLs
URL Status Response Body
http://localhost:3000/ 200 Welcome to CIIT Training Institute!
http://localhost:3000/courses 404 404 - Page Not Found

10. Response Execution Flow

HTTP Response Flow Diagram
Client Sends Request
↓
Server Processes Request
↓
Set Status Code and Headers
For example, 200 and Content-Type.
↓
Write Response Body
Text, HTML, JSON, or other data.
↓
Call res.end()
Complete the response and return it to the client.

11. Common Mistakes

Mistake Correct Approach
Forgetting to call res.end(). Complete the response after sending the required body.
Sending HTML with a plain-text content type. Use an appropriate content type such as text/html.
Sending a JavaScript object directly as the response body. Convert the object using JSON.stringify().
Returning 200 for every request. Use appropriate status codes, such as 404 for missing resources.
Writing data after res.end(). Send all response data before completing the response.

12. Important Points to Remember

  • An HTTP response contains a status code, headers, and optionally a body.
  • res.writeHead() sets the status code and headers.
  • res.write() writes part of the response body.
  • res.end() completes the response.
  • Use text/plain for plain text and text/html for HTML.
  • Use JSON.stringify() to serialize a JavaScript object as JSON.
  • Use suitable HTTP status codes to communicate the result of a request.

Summary

In this lesson, we learned how to send HTTP responses using Node.js, set status codes and headers, return plain text, HTML and JSON, use res.write() and res.end(), and handle missing resources with a 404 response. Examples involving Samadhan, Pradnya, and CIIT Training Institute demonstrate practical response handling.