Advanced Example 1: Building a Custom HTTP Server with Node.js 🌐

This example demonstrates how to create a simple HTTP server using Node.js, handling GET requests and serving dynamic content.

Step-by-Step Guide

  1. Initialize a new project
    Run npm init -y to create a package.json file.

  2. Create the server file
    Save the following code as server.js:

const http = require('http');

http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/hello') {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello, World! 🎉');
  } else {
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end('Not Found 😢');
  }
}).listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});
  1. Run the server
    Execute node server.js and navigate to http://localhost:3000/hello in your browser.

Key Features

  • ✅ Handles GET requests
  • 📁 Serves static/dynamic content
  • 🌐 Works with Node.js

For more advanced topics, check out our Advanced Topics documentation.

Node_js_Server