</>
Skip to content
Node.js lessons (33/44)

Node.js — Web Server

Basic Web Server

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

const server = http.createServer((req, res) => {
    let filePath = path.join(__dirname, 'public', req.url === '/' ? 'index.html' : req.url);
    
    fs.readFile(filePath, (err, content) => {
        if (err) {
            res.writeHead(404);
            res.end('Not Found');
        } else {
            res.writeHead(200);
            res.end(content);
        }
    });
});

server.listen(3000);

MIME Types

const mimeTypes = {
    '.html': 'text/html',
    '.css': 'text/css',
    '.js': 'application/javascript',
    '.json': 'application/json',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.gif': 'image/gif'
};

Serving Static Files

const express = require('express');
const app = express();

app.use(express.static('public'));

app.listen(3000);

Mini Practice

  1. Create a basic web server
  2. Serve HTML files
  3. Set proper MIME types
  4. Use Express static middleware

Up Next

Continue with Express — the Express.js framework.

Related Topics

Frequently Asked Questions about Web Server

What is Web Server in Node.js?

Web Server is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Web Server?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Web Server.

Why is Web Server important in Node.js?

Web Server is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.