Simple HTTP File Server

2.2.1 · maintenance · verified Sun Apr 19

The `file-server` package provides a minimalistic HTTP file and directory serving library for Node.js, currently at stable version 2.2.1. It offers a low-level API to create custom file-serving handlers, supporting features like ETag-based caching, configurable `max-age`, and GZIP compression (inferred from package keywords). Updates appear infrequent, suggesting a maintenance-focused cadence rather than active feature development, with the last major update (v2.0.0) removing support for Node.js versions older than 8. Its key differentiators include a callback-based error handling system and explicit control over MIME types and directory access, offering a fundamental building block for custom static file servers rather than an opinionated middleware solution.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate `FileServer`, create handlers for a specific file and a directory, and integrate them with a basic Node.js HTTP server. It also shows how to gracefully close the file watchers.

const FileServer = require('file-server');
const http = require('http');
const path = require('path');
const fs = require('fs');

// Create a dummy file and directory for the example
const tempDir = path.join(__dirname, 'temp-static');
const robotTxtPath = path.join(tempDir, 'robots.txt');
const imagesDir = path.join(tempDir, 'images');

if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir);
if (!fs.existsSync(imagesDir)) fs.mkdirSync(imagesDir);
fs.writeFileSync(robotTxtPath, 'User-agent: *\nDisallow: /private/', 'utf8');
fs.writeFileSync(path.join(imagesDir, 'test.png'), 'dummy image content', 'utf8'); // In a real scenario, this would be binary

const fileServer = new FileServer((error, request, response) => {
    response.statusCode = error.code || 500;
    response.end(`Error: ${error.message || 'Internal Server Error'}`);
});

const serveRobots = fileServer.serveFile(robotTxtPath, 'text/plain');
const serveImagesDirectory = fileServer.serveDirectory(imagesDir, {
    '.png': 'image/png',
    '.jpg': 'image/jpeg'
});

const server = http.createServer((request, response) => {
    if (request.url === '/robots.txt') {
        serveRobots(request, response);
    } else if (request.url.startsWith('/images/')) {
        // The serveDirectory method automatically infers filename from request.url if not provided.
        serveImagesDirectory(request, response);
    } else {
        response.statusCode = 404;
        response.end('Not Found');
    }
});

const PORT = 8080;
server.listen(PORT, () => {
    console.log(`File server listening on http://localhost:${PORT}`);
    console.log(`Try: http://localhost:${PORT}/robots.txt`);
    console.log(`Try: http://localhost:${PORT}/images/test.png`);
}).on('close', () => {
    fileServer.close(() => {
        console.log('File server watchers closed.');
        // Cleanup temporary files/directories after server closes
        fs.rmSync(tempDir, { recursive: true, force: true });
    });
});

// To stop the server gracefully
// process.on('SIGINT', () => { server.close(); });

view raw JSON →