Node-Static

0.7.11 · abandoned · verified Sun Apr 19

`node-static` is a legacy module designed for serving static files over HTTP, adhering to RFC 2616, including support for conditional GET and HEAD requests. The last published version, 0.7.11, dates back over eight years, targeting very old Node.js environments (engine requirement `node >= 0.4.1`). It simplifies static file serving by abstracting `Cache-Control` headers and basic error handling, allowing developers to specify a root directory and cache duration. Due to its age and lack of maintenance, it is now considered abandoned. Its API heavily relies on callback patterns and older Node.js `http` module stream handling, which are not idiomatic in modern JavaScript development, making it unsuitable for contemporary projects.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart sets up a basic HTTP server using `node-static` to serve files from a `./public` directory. It demonstrates the module's core `Server` instantiation, `serve` method, and basic error handling with an old Node.js `http` stream pattern.

var static = require('node-static');
var http = require('http');

// Create a node-static server instance to serve the './public' folder.
// Ensure a 'public' directory exists in your project root with some static files.
var file = new static.Server('./public', {
    cache: 3600, // Cache files for 1 hour (default)
    headers: {
        'X-Powered-By': 'node-static'
    }
});

http.createServer(function (request, response) {
    // This pattern for handling request 'end' and 'resume' is for older Node.js versions.
    request.addListener('end', function () {
        file.serve(request, response, function (err, result) {
            if (err) {
                console.error("Error serving " + request.url + " - " + err.message);
                // Respond manually to the client if an error occurs
                response.writeHead(err.status || 500, err.headers || { 'Content-Type': 'text/plain' });
                response.end("Error serving file: " + err.message);
            }
        });
    }).resume(); // Important for older Node.js to ensure stream is read
}).listen(8080, function() {
    console.log('node-static server running on http://localhost:8080');
    console.log('Serving files from ./public');
});

view raw JSON →