A basic HTTP server based in Node.js

CK CK 3788 
Created at
Updated at  
543 0 0

Here's a simple Node.js example that demonstrates a basic HTTP server:

Basic HTTP Server in Node.js

// Load the http module to create an HTTP server.
const http = require('http');

// Configure the HTTP server to respond with "Hello, World!" to all requests.
const server = http.createServer((req, res) => {
  // Set the response HTTP header with HTTP status and Content type
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, World!\n');
});

// Listen on port 8080, IP defaults to 127.0.0.1
server.listen(8080, '127.0.0.1', () => {
  console.log('Server running at http://127.0.0.1:8080/');
});

 

How it works:

  • http module: This module is built into Node.js and provides the functionality to create an HTTP server.
  • http.createServer(): This function creates a new HTTP server and takes a callback function that will be executed each time a request is received. The callback function receives two arguments:
    • req: An object containing information about the request (e.g., URL, headers, etc.).
    • res: An object that can be used to send a response back to the client.
  • server.listen(): This method makes the server listen for incoming connections on a specified port (3000 in this case).

 

Running the example:

  1. Save the code to a file, e.g., server.js.
  2. Run the server using Node.js:

    node server.js
  3. Open a browser and go to http://127.0.0.1:8080/ to see the message "Hello, World!".

 

If you want to use local files, you can serve local files like index.html or images using Node.js. To do this, you'll typically want to use the fs (File System) module to read the files and serve them via the HTTP server. Here's an example that serves an index.html file and images from the local filesystem:

 

Example: Serving Local Files with Node.js

Directory Structure:

/myapp
  ├── server.js
  ├── index.html
  └── images
      └── logo.png

 

index.html (Example)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Node.js Server</title>
</head>
<body>
    <h1>Hello from Node.js!</h1>
    <img src="/images/logo.png" alt="Logo">
</body>
</html>

 

server.js

const http = require('http');
const fs = require('fs');
const path = require('path');

// MIME types mapping for different file extensions
const mimeTypes = {
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.css': 'text/css',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.gif': 'image/gif',
    '.svg': 'image/svg+xml',
    '.json': 'application/json',
    '.woff': 'font/woff',
    '.woff2': 'font/woff2',
    '.ttf': 'font/ttf',
    '.eot': 'application/vnd.ms-fontobject',
    '.otf': 'font/otf',
    '.wasm': 'application/wasm'
};

// Create an HTTP server
const server = http.createServer((req, res) => {
    // Normalize URL by removing querystring, optional slashes, and making it lowercase
    let filePath = '.' + req.url;
    if (filePath == './') {
        filePath = './index.html';
    }

    // Determine the content type based on the file extension
    const extname = String(path.extname(filePath)).toLowerCase();
    const contentType = mimeTypes[extname] || 'application/octet-stream';

    // Read the requested file from the filesystem
    fs.readFile(filePath, (error, content) => {
        if (error) {
            if (error.code == 'ENOENT') {
                // File not found
                fs.readFile('./404.html', (err, content) => {
                    res.writeHead(404, { 'Content-Type': 'text/html' });
                    res.end(content, 'utf-8');
                });
            } else {
                // Some server error
                res.writeHead(500);
                res.end(`Server Error: ${error.code}`);
            }
        } else {
            // Serve the file
            res.writeHead(200, { 'Content-Type': contentType });
            res.end(content, 'utf-8');
        }
    });
});

// Listen on port 8080
server.listen(8080, '127.0.0.1', () => {
    console.log('Server running at http://127.0.0.1:8080/');
});

 

How it works:

  1. File Path Normalization: The code normalizes the requested file path by stripping out any query strings and adding a default to index.html if no file is specified.
  2. MIME Type Detection: The content type (MIME type) is determined based on the file extension to ensure the correct type is sent in the response headers.
  3. File Reading: The fs.readFile() method reads the file from the local filesystem and serves it. If the file is not found, a 404.html file (if it exists) is served instead.

 

Running the Example:

  1. Save the code to server.js.
  2. Ensure you have an index.html file and any other files (like images) in the correct directory.
  3. Run the server using Node.js:

    node server.js
    
  4. Visit http://127.0.0.1:8080/ in your browser. You should see the HTML file and any linked images or other assets being served.
Tags Node.js Web Server Server Web Server Facebook X
Comments 0
Similar posts
  1. Multi-threaded Web Server based in Node.js
    866
  2. Node.js-based Web Server supporting multiple path
    602
  3. "502 Bad Gateway" Error easy to happen at the combination of nginx and node.js in AWS Elastic Beanstalk
    10,495
  4. Uvicorn, Gunicorn: Proving Your Production Prowess
    401
  1. Get client IP address and user agent in Node.js
    1,531
  2. forEach method in JavaScript when working with arrays
    666
  3. CRC32B function code in Javascript
    1,843
  4. A simple Javascript class example with static method for Node.js
    661
  5. Setting a Common Path for require() in Node.js
    1,005
  6. Import all JS files in a specific folder for Node.js programming
    1,731
  7. A simple example to access a PostgreSQL database in Node.js
    1,100
  8. Node.js code example to access Google BigQuery
    1,183
  9. Investigation on package.js for Node.js source code
    823
  10. Using MySQL in Node.js
    484
  11. A Node.js script that checks if a module is installed before requiring it
    773
  12. Worker Threads and Mutual Exclusion in Node.js
    466
  13. Using a module in the external class itself without creating an instance in Node.js
    350
  14. Node.js external modules
    433
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    29
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    55
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    49
  4. How do I create animated background for Google Meet?
    22,892
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    271
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    103
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    168
  8. Array of arguments passed to script in PHP
    97
  9. Invalid Auction Storms in Ad Tech
    106
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    207
  11. The Two Clocks of Ad Server Architecture
    77
  12. Frequency Cap Architecture Overview
    526
  13. Collecting Proof-of-Play from 100,000 Screens
    152
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    302
  15. What is RedisVL?
    114
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    246
  17. TPU & GPU Cluster Management Tools
    257
  18. The Concept of Scaffolding in AI Agents
    244
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    596
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    267
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    353
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    206
  23. Machine Learning: Training vs. Ranking
    229
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    202
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    671
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    200
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    232