Server

Table of Contents

Description

A lightweight HTTP server utility for serving static files and handling route patterns with wildcard support.

Basic Usage

import { Server } from '../utils/Server.js';

const server = new Server();
server
  .static('/assets', './public')
  .route('/api/*.json', async (req, res) => {
    // Handle JSON requests
  });

await server.listen(8080);

Static File Serving

// Serve entire directories
server.static('/assets', './public');
server.static('/docs', './documentation');

// Serve single files with custom headers
server.route('/style.css', async (req, res) => {
  await server.serveFile('./styles/main.css', res, {
    'Cache-Control': 'no-cache'
  });
});

Route Patterns

Routes support wildcard patterns for flexible path matching:

// Match specific file types
server.route('/api/*.json', handler);

// Match files in subdirectories
server.route('/docs/**/*.html', handler);

// Match everything under a path
server.route('/assets/**/*', handler);

JavaScript Reference

Constructor

new Server()

Creates a new server instance.

Requirements

Methods

route(path: string, handler: Function, methods?: string[]): Server

Registers a route handler with optional HTTP method restrictions. Returns this for chaining.

static(urlPath: string, dirPath: string): Server

Serves an entire directory of static files. Returns this for chaining.

serveFile(filePath: string, res: Response, headers?: object): Promise<void>

Serves a single file with appropriate MIME type and optional headers.

listen(port?: number): Promise<http.Server>

Starts the server on the specified port. Returns a Promise that resolves to the server instance.

Static Members

static mimeTypes: Record<string, string>

MIME type mappings for file extensions.

static textExtensions: string[]

List of file extensions that should be served as text.

static getMimeType(filePath: string): string

Returns the appropriate MIME type for a file based on its extension.