HTTP Static Content Middleware for Node.js

1.2.2 · maintenance · verified Wed Apr 22

This middleware is part of the `atmajs` ecosystem, designed for handling static file serving in Node.js HTTP servers. It provides features like caching, gzipping, and range requests for optimized delivery of various content types including HTML, scripts, images, and videos. It supports custom MIME types, encoding configurations, and integrates seamlessly with `atma-server` and Connect-style middleware stacks. Currently at version 1.2.2, its release cadence is not explicitly defined, but it appears to be a stable, mature component within its specific framework, primarily targeting CommonJS environments. Key differentiators include its tight integration with `atma-io` for advanced file reading and its support for virtual files and custom file `read` middlewares, offering more flexibility than generic static servers.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates setting up a basic Node.js HTTP server to serve static files from a 'public' directory, including custom MIME types and caching.

const http = require('http');
const staticContent = require('static-content');

// Create a static content middleware instance
const staticMiddleware = staticContent.create({
    base: './public',
    mimeTypes: {
        'application/javascript': ['mjs']
    },
    extensions: {
        'text/html': {
            encoding: 'UTF-8',
            maxAge: 3600 // Cache for 1 hour
        }
    }
});

// Create a simple HTTP server using the middleware
http.createServer((req, res) => {
    // The middleware handles static content requests
    staticMiddleware(req, res, () => {
        // If static content is not found, handle dynamic content or return 404
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('404 Not Found');
    });
}).listen(5777, () => {
    console.log('Static server running on http://localhost:5777');
    console.log('Serving files from ./public');
});

view raw JSON →