Creating the Server

The server is created using Node's built-in http module. No Express, no third-party framework — just the raw Node.js API.

import http from "http";

const server = http.createServer((req, res) => {
  // handle request
});

server.listen(3000, () => {
  console.log("Server running at http://localhost:3000");
});

Serving Static Files

fs.readFile() reads each HTML file from the public/ folder and sends it as the response. The path module builds safe, cross-platform file paths.

import fs from "fs";
import path from "path";

const serveFile = (res, filePath) => {
  fs.readFile(filePath, (err, data) => {
    if (err) { res.writeHead(404); res.end("Not Found"); return; }
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end(data);
  });
};

Request Logging

Every request is logged to the console with a timestamp and also appended to requests.log using fs.appendFile().

const logRequest = (req) => {
  const log = `[${new Date().toISOString()}] ${req.method} ${req.url}`;
  console.log(log);
  fs.appendFile("requests.log", log + "\n", (err) => {
    if (err) console.error("Logger error:", err);
  });
};

Key Concepts

  • http.createServer: Creates the server and handles every request
  • req.url: The URL path the browser requested
  • res.writeHead: Sets the status code and response headers
  • fs.readFile: Reads a file asynchronously from disk
  • fs.appendFile: Appends a line to the log file
  • path.join: Builds safe file paths across OS platforms
  • nodemon: Watches for file changes and auto-restarts the server