Building an HTTP Server

🌿 Node.js Lesson 6 Intermediate

Node.js ships with a built-in http module that lets you create web servers without any external framework. Understanding it deeply is crucial before using Express.js.

1 Creating a Basic HTTP Server
JavaScript — http module server
const http = require('http');
const url  = require('url');

const server = http.createServer((req, res) => {
  // Parse URL and query string
  const parsedUrl = url.parse(req.url, true);
  const pathname  = parsedUrl.pathname;
  const query     = parsedUrl.query;

  console.log(req.method, pathname);

  // Route handling
  if (pathname === '/' && req.method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ message: 'Welcome to My Node API', status: 'ok' }));

  } else if (pathname === '/echo' && req.method === 'POST') {
    let body = '';
    req.on('data', chunk => { body += chunk.toString(); });
    req.on('end', () => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ echo: JSON.parse(body) }));
    });

  } else {
    res.writeHead(404, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ error: 'Route not found' }));
  }
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});
2 Serving Static HTML Files
JavaScript — Serve static files
const http = require('http');
const fs   = require('fs');
const path = require('path');

const MIME = {
  '.html': 'text/html',
  '.css':  'text/css',
  '.js':   'application/javascript',
  '.json': 'application/json',
  '.png':  'image/png'
};

const server = http.createServer(async (req, res) => {
  const safePath = path.join(__dirname, 'public', req.url === '/' ? 'index.html' : req.url);
  const ext = path.extname(safePath);

  try {
    const data = await fs.promises.readFile(safePath);
    res.writeHead(200, { 'Content-Type': MIME[ext] || 'text/plain' });
    res.end(data);
  } catch {
    res.writeHead(404);
    res.end('Not Found');
  }
});

server.listen(3000);
3 Code Challenge
Challenge: Extend the HTTP server above to support a PUT /users/:id route that reads the request body JSON and prints the updated user data. Handle missing routes with a proper 404 response.