or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-node-http-server

A very simple and fast http server for node, bash, and spawnable from C, Python etc.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/node-http-server@8.1.x

To install, run

npx @tessl/cli install tessl/npm-node-http-server@8.1.0

index.mddocs/

Node HTTP Server

Node HTTP Server is a lightweight, zero-dependency HTTP/HTTPS server for Node.js that provides both programmatic API and CLI functionality. It features configurable server settings, HTTPS support, multiple domain handling, proxy capabilities, template processing through lifecycle hooks, and extensible server architecture.

Package Information

  • Package Name: node-http-server
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install node-http-server

Core Imports

const server = require('node-http-server');

The package exports a pre-instantiated Server instance for immediate use, plus access to the Server class and Config class for creating custom instances.

Basic Usage

const server = require('node-http-server');

// Simple server deployment
server.deploy({
    port: 8000,
    root: './public',
    verbose: true
});

// With ready callback
server.deploy({
    port: 3000,
    root: __dirname + '/app'
}, function(server) {
    console.log(`Server running on port ${server.config.port}`);
});

Architecture

Node HTTP Server is built around several key components:

  • Server Class: Main server class providing HTTP/HTTPS functionality with lifecycle hooks
  • Config Class: Configuration management with sensible defaults and validation
  • Lifecycle Hooks: Extensible request/response processing pipeline (onRawRequest, onRequest, beforeServe, afterServe)
  • Static File Serving: Built-in file serving with MIME type detection and caching control
  • Multi-Protocol Support: HTTP and HTTPS with automatic certificate handling
  • Multi-Domain Support: Virtual host capabilities with domain-specific document roots

Capabilities

Server Deployment

Deploy HTTP and/or HTTPS servers with comprehensive configuration options.

/**
 * Deploy server with configuration
 * @param {Object} userConfig - Configuration object to merge with defaults
 * @param {Function} readyCallback - Called when server starts
 */
server.deploy(userConfig, readyCallback);

/**
 * Server class for creating custom instances
 * @param {Object} userConfig - Configuration object to merge with defaults
 */
const Server = server.Server;
const myServer = new Server(userConfig);

Usage Examples:

const server = require('node-http-server');

// Basic HTTP server
server.deploy({
    port: 8080,
    root: './public'
});

// HTTPS server
server.deploy({
    port: 8000,
    https: {
        privateKey: '/path/to/private.key',
        certificate: '/path/to/certificate.crt',
        port: 443
    }
});

// Multiple servers
const Server = server.Server;
const server1 = new Server({ port: 8000 });
const server2 = new Server({ port: 9000 });

server1.deploy();
server2.deploy();

Request Lifecycle Hooks

Extensible hooks for customizing request processing pipeline.

/**
 * Raw request hook - called before any processing
 * @param {http.IncomingMessage} request - Raw HTTP request
 * @param {http.ServerResponse} response - HTTP response object
 * @param {Function} serve - Serve function reference
 * @returns {boolean|void} - Return truthy to bypass normal processing
 */
server.onRawRequest = function(request, response, serve) {};

/**
 * Request hook - called after request decoration
 * @param {Object} request - Decorated request with uri, query properties
 * @param {http.ServerResponse} response - HTTP response object
 * @param {Function} serve - Serve function reference
 * @returns {boolean|void} - Return truthy to bypass normal processing
 */
server.onRequest = function(request, response, serve) {};

/**
 * Before serve hook - called before serving response, allows body modification
 * @param {Object} request - Decorated request object
 * @param {http.ServerResponse} response - HTTP response object
 * @param {RefString} body - Response body as RefString for modification
 * @param {RefString} encoding - Response encoding as RefString for modification
 * @param {Function} serve - Serve function reference
 * @returns {boolean|void} - Return truthy to handle serving manually
 */
server.beforeServe = function(request, response, body, encoding, serve) {};

/**
 * After serve hook - called after response is sent
 * @param {Object} request - Decorated request object
 */
server.afterServe = function(request) {};

Usage Examples:

const server = require('node-http-server');

// API endpoint handling
server.onRequest = function(request, response, serve) {
    if (request.uri.pathname.startsWith('/api/')) {
        const data = { message: 'Hello from API', path: request.uri.pathname };
        serve(request, response, JSON.stringify(data));
        response.setHeader('Content-Type', 'application/json');
        return true; // Skip file serving
    }
    return false; // Continue normal processing
};

// Template processing
server.beforeServe = function(request, response, body, encoding) {
    if (response.getHeader('Content-Type') === 'text/html') {
        const timestamp = new Date().toISOString();
        body.value = body.value.replace('{{timestamp}}', timestamp);
    }
};

// Request logging
server.afterServe = function(request) {
    console.log(`Served: ${request.uri.pathname} at ${new Date()}`);
};

server.deploy({ port: 8000, root: './public' });

Configuration Management

Comprehensive configuration system with defaults and validation.

/**
 * Configuration class with default values
 * @param {Object} userConfig - Configuration overrides
 */
const Config = server.Config;
const config = new Config(userConfig);

interface ConfigOptions {
    /** Enable verbose logging */
    verbose: boolean;
    /** HTTP server port */
    port: number;
    /** Document root directory */
    root: string;
    /** Server domain/hostname */
    domain: string;
    /** Enable logging or specify log file path */
    log: boolean | string;
    /** Custom logging function */
    logFunction: Function;
    /** Multiple domain configuration */
    domains: Object;
    /** Server-specific settings */
    server: {
        /** Default index file */
        index: string;
        /** Disable caching headers */
        noCache: boolean;
        /** Server timeout in milliseconds */
        timeout: number;
    };
    /** HTTPS configuration */
    https: {
        /** Certificate Authority file path */
        ca: string;
        /** Private key file path */
        privateKey: string;
        /** Certificate file path */
        certificate: string;
        /** Certificate passphrase */
        passphrase: string | boolean;
        /** HTTPS port */
        port: number;
        /** HTTPS only mode */
        only: boolean;
    };
    /** MIME type mappings */
    contentType: Object;
    /** Restricted file types */
    restrictedType: Object;
    /** Error page configuration */
    errors: {
        headers: Object;
        404: string;
        415: string;
        403: string;
        500: string;
    };
}

Usage Examples:

const server = require('node-http-server');
const Config = server.Config;

// Custom configuration instance
const config = new Config({
    port: 9000,
    verbose: true,
    server: {
        index: 'home.html',
        noCache: false
    }
});

const customServer = new server.Server(config);
customServer.deploy();

// Multiple domains
server.deploy({
    port: 8000,
    domain: 'localhost',
    domains: {
        'api.example.com': '/path/to/api/root',
        'www.example.com': '/path/to/www/root'
    }
});

HTTPS Support

Built-in HTTPS server support with certificate handling.

interface HTTPSConfig {
    /** Certificate Authority file path */
    ca?: string;
    /** Private key file path */
    privateKey: string;
    /** Certificate file path */
    certificate: string;
    /** Certificate passphrase */
    passphrase?: string | boolean;
    /** HTTPS port */
    port?: number;
    /** HTTPS only mode - disables HTTP server */
    only?: boolean;
}

Usage Examples:

const server = require('node-http-server');

// HTTPS with HTTP redirect
server.deploy({
    port: 8000,
    https: {
        privateKey: './certs/server.key',
        certificate: './certs/server.crt',
        port: 8443
    }
});

// HTTPS only
server.deploy({
    https: {
        privateKey: './certs/server.key',
        certificate: './certs/server.crt',
        port: 443,
        only: true
    }
});

// HTTPS with CA and passphrase
server.deploy({
    https: {
        privateKey: './certs/server.key',
        certificate: './certs/server.crt',
        ca: './certs/ca.crt',
        passphrase: 'mypassword',
        port: 8443
    }
});

Manual Response Handling

Direct response serving for custom content delivery.

/**
 * Manual serve function for custom responses
 * @param {Object} request - Request object
 * @param {http.ServerResponse} response - Response object
 * @param {string} body - Response body content
 * @param {string} encoding - Response encoding (default: 'utf8')
 */
server.serve(request, response, body, encoding);

/**
 * Manual file serving function
 * @param {string} filename - File path to serve
 * @param {boolean} exists - Whether file exists
 * @param {Object} request - Request object
 * @param {http.ServerResponse} response - Response object
 */
server.serveFile(filename, exists, request, response);

Usage Examples:

const server = require('node-http-server');

server.onRequest = function(request, response, serve) {
    if (request.uri.pathname === '/status') {
        response.setHeader('Content-Type', 'application/json');
        serve(request, response, JSON.stringify({
            status: 'ok',
            timestamp: Date.now(),
            uptime: process.uptime()
        }));
        return true;
    }
    
    if (request.uri.pathname === '/download') {
        const filePath = './files/document.pdf';
        response.setHeader('Content-Type', 'application/pdf');
        response.setHeader('Content-Disposition', 'attachment; filename="document.pdf"');
        server.serveFile(filePath, true, request, response);
        return true;
    }
};

server.deploy({ port: 8000 });

CLI Usage

Command-line interface for quick server deployment.

# Basic usage
node-http-server

# With configuration
node-http-server port=3000 verbose=true root=/path/to/files

# Available CLI options
node-http-server port=8080 domain=localhost index=home.html noCache=false verbose=true

All Config class properties can be set via CLI arguments using key=value format.

Types

/**
 * Reference string wrapper for pass-by-reference modification
 */
class RefString {
    constructor(value?: string);
    
    /** The wrapped string value */
    get value(): string;
    set value(value: string): string;
}

/**
 * Decorated request object with additional properties
 */
interface DecoratedRequest extends http.IncomingMessage {
    /** Parsed URI with protocol, host, pathname, query properties */
    uri: {
        protocol: string;
        host: string;
        hostname: string;
        port: number;
        pathname: string;
        query: Object;
    };
    /** Raw URL path */
    url: string;
    /** Document root being used for this request */
    serverRoot: string;
    /** Request body content */
    body: string;
}

/**
 * Server instance with configuration and lifecycle hooks
 */
interface ServerInstance {
    /** Server configuration */
    config: ConfigOptions;
    /** HTTP server instance */
    server?: http.Server;
    /** HTTPS server instance */
    secureServer?: https.Server;
    /** Deploy method */
    deploy(userConfig?: Object, readyCallback?: Function): void;
    /** Lifecycle hooks */
    onRawRequest(request: http.IncomingMessage, response: http.ServerResponse, serve: Function): boolean | void;
    onRequest(request: DecoratedRequest, response: http.ServerResponse, serve: Function): boolean | void;
    beforeServe(request: DecoratedRequest, response: http.ServerResponse, body: RefString, encoding: RefString, serve: Function): boolean | void;
    afterServe(request: DecoratedRequest): void;
    /** Utility methods */
    serve(request: DecoratedRequest, response: http.ServerResponse, body: string, encoding?: string): void;
    serveFile(filename: string, exists: boolean, request: DecoratedRequest, response: http.ServerResponse): void;
}