>_
EngineeringNotes
← Back to Node.js & Runtimes
Module 05

HTTP Module (Core Native Server)

The explicit foundation of Express.js. Learn to organically create web servers, carefully handle HTTP requests and efficiently process structural responses.

01

What is the HTTP Module?

Definition: The standard HTTP module native directly in Node.js structurally allows you to dynamically create a functional web server manually handling all basic incoming HTTP connections and correctly triggering sequential responses natively.

Key Engineering Concept

This is the underlying fundamental execution foundation powering Express.js infrastructure.

  • Everything Express automatically manages essentially wraps native logic surrounding: http.createServer()
02

Creating Your First Server Core

basic-server.js
javascript
import http from 'http';

const server = http.createServer((req, res) => {
    res.end("Hello World");
});

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

Execution Operation Breakdown

  • The local development server process is intrinsically created.
  • It establishes a permanent listening sequence tied strictly to port 3000.
  • For essentially every mapped incoming URL request object → The designated fallback callback code executes completely.
03

Processing Variables: req and res

📥 req (Request Object)

Contains distinctly sourced metadata payloads originating from the executing client:

  • URL Path → req.url
  • Verb Method → req.method
  • Data Headers → req.headers

📤 res (Response Object)

Employed systematically to resolve and transmit compiled data payloads successfully back:

  • res.write(data)
  • res.end(data)
  • res.setHeader(...)
request-response.js
javascript
const server = http.createServer((req, res) => {
    // Extrapolate payload data dynamically
    console.log(req.method, req.url);

    // Sequentially assemble final payload output
    res.write("Hello ");
    res.end("World");
});
04

Fundamental Path Routing (Manual)

Without Defined Target Routing

Every distinctly mapped request logically renders universally identical global outcome responses indiscriminately.

With Manual Execution Routing

javascript
javascript
const server = http.createServer((req, res) => {
    if (req.url === "/") {
        res.end("Home Page");
    } else if (req.url === "/about") {
        res.end("About Page");
    } else {
        res.statusCode = 404;
        res.end("Not Found");
    }
});
Developer Insight: This fundamentally demonstrates exactly why bare manual Node routing scales remarkably inefficiently. Rapidly expanding switch-case chains force immense repetitive overhead natively cleanly abstracted completely away later employing external frameworks primarily resolving scaling patterns dynamically using Express router logic integrations.
05

Parsing Request Target HTTP Methods

javascript
javascript
if (req.method === "GET") {
    res.end("Process GET operation");
} else if (req.method === "POST") {
    res.end("Process POST payload operation");
}
Operational Focus MethodIntegration Meaning Specification
GETSafely securely request and fetch server configuration processing / payload data.
POSTSecurely transmit creation or internal processing variables to the backend execution.
PUTCommit update modifiers explicitly overwriting previous structural assignments.
DELETECommand system destruct parameters directly cleanly resolving logic entirely.
06

Formatting JSON Responses

json-response.js
javascript
const server = http.createServer((req, res) => {
    res.setHeader("Content-Type", "application/json");

    res.end(JSON.stringify({
        name: "Shivam",
        role: "Developer"
    }));
});
Formatting Important Rule: Standard web configurations mandate that you must always explicitly stringify JSON (using JSON.stringify) prior to sending output bytes payload across generic stream arrays.
07

Parsing Request Body Dynamics (POST)

⚠️ Technical constraint: Node natively skips parsing chunk payloads structurally altogether automatically.
extract-body.js
javascript
const server = http.createServer((req, res) => {
    if (req.method === "POST") {
        let body = "";

        req.on("data", chunk => {
            body += chunk.toString();
        });

        req.on("end", () => {
            console.log(body);
            res.end("Data payload functionally received successfully!");
        });
    }
});
Implementation Insight:The internal Request body inherently arrives purely as an encoded Buffer stream. Chunks natively collect incrementally and must manually resolve across the "end" processing event context listener.
08

Serving Structural HTML & Static Data Targets

Serving HTML Architecture Context

serve-html.js
javascript
import fs from 'fs';

const server = http.createServer((req, res) => {
    const html = fs.readFileSync('index.html');

    res.setHeader("Content-Type", "text/html");
    res.end(html);
});

Serving Rendered Static Context Targets (CSS / Script Bundles)

serve-css.js
javascript
if (req.url === "/style.css") {
    const css = fs.readFileSync('style.css');
    res.setHeader("Content-Type", "text/css");
    res.end(css);
}

Routing Drawbacks Identification

Attempting manual content type declaration assignments scales incredibly poorly. Each distinct mime type enforces specific repetitive mapping constraints. This explicit difficulty validates exactly why standard implementations integrate Express directly.

09

Status Headers & Metadata Integrations

HTTP Status Code Assignments

CodeAssigned Diagnostic Meaning
200Success OK Resolution
201Created Instance Resolution
400Target Rejection Bad Request
404Not Directly Found Path
500Total Complete Server Error
javascript
javascript
// Explicit definition
res.statusCode = 404;
res.end("Not Found");

Custom Header Implementation Metadata

headers.js
javascript
res.setHeader("Content-Type", "application/json");
res.setHeader("X-Custom-Header", "NodeServer");
  • Standard Requirements Use Cases: Assigning Content type mappings consistently.
  • Declaring security constraints and explicit JWT Authorization layers.
  • Implementing critical CORS validation configurations strictly.
10

Integrating Streams natively via HTTP

Example Configuration: Extremely Efficient System File Serving

stream-web.js
javascript
import fs from 'fs';
import http from 'http';

const server = http.createServer((req, res) => {
    const stream = fs.createReadStream('scale_file.txt');
    stream.pipe(res);
});

No Memory Faults

Zero total operational ram constraints observed via buffering.

Velocity Return Limit

Exceptionally fastest immediate chunk return possible natively.

Production Verified

The absolute primary implementation standard adopted broadly.

11

Core Interview Assessment

What essentially is the HTTP module?
Answer:A built-in native integration configuration allowing the manual creation of operational system servers processing incoming HTTP procedural requests and explicitly generating resulting output parameters natively.
What characterize 'req' and 'res' strictly?
Answer:req directly identifies incoming payload request components; res identifies generated outgoing returning connection sequences natively bound.
Elaborate essentially how raw web routing integrates.
Answer:By explicitly conditionally checking the defined req.url parameter assigned endpoints dynamically bound against utilizing req.method request operations.
Why is processing body configurations mandated manual operation?
Answer:Because natively Node streams data metrics logically incrementally via sequence parts strictly instead of instantly fully buffering constraints resulting in mandatory collection combinations securely stringently.
Why deploy streams structurally resolving direct HTTP integrations?
Answer:To exponentially streamline heavily dense volume variables efficiently circumventing all explicitly scaled server resource memory ceiling crashes reliably.
Explicitly identify differences tracking res.write() and res.end().
Answer:Write functions procedurally continuously sequentially sending payload chunks iteratively; end explicitly declares the terminal closure state securely safely ceasing outgoing connections efficiently precisely.

Final Target Mental Model Configuration

Client InterfaceInitiates Output Connect
req ↔ res
Node JS Processing Core EngineReturns Output Parameter Sequences