Node.js Static File Server

2.2.1 · abandoned · verified Sun Apr 19

The `static-server` package provides a minimalistic HTTP server explicitly designed to serve static files from a local directory. It is primarily intended for local development, rapid prototyping, or testing scenarios, with its maintainers stating it is "obviously not" suitable for production environments and "preferably not" for high-traffic applications. The current stable version, 2.2.1, was released several years ago, and the project appears to be abandoned, with no significant updates in a long time. It differentiates itself by its extreme simplicity and minimal configuration options, serving only static resources without support for server-side scripting languages like PHP, Ruby, or Python. It's a foundational utility rather than a feature-rich web server.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart initializes and starts a static HTTP server on port 1337, serving files from the current directory. It demonstrates basic event listeners for requests and responses, and explicitly enables CORS and symlink following. A temporary `index.html` is created for immediate testing.

var StaticServer = require('static-server');
var server = new StaticServer({
  rootPath: '.',            // required, the root of the server file tree
  port: 1337,               // required, the port to listen
  name: 'my-http-server',   // optional, will set "X-Powered-by" HTTP header
  host: '127.0.0.1',        // optional, defaults to any interface (use '127.0.0.1' for local only)
  cors: '*',                // optional, defaults to undefined, '*' allows all origins
  followSymlink: true,      // optional, defaults to a 404 error if not true
  templates: {
    index: 'index.html',    // optional, defaults to 'index.html'
    notFound: '404.html'    // optional, defaults to undefined
  }
});

server.start(function () {
  console.log('Server listening to', server.port);
  console.log('Serving files from', server.rootPath);
  // Create a dummy index.html for demonstration
  require('fs').writeFileSync('index.html', '<h1>Hello from static-server!</h1>');
  console.log('Created a temporary index.html. Access at http://' + server.host + ':' + server.port);
});

server.on('request', function (req, res) {
  // Log basic request info
  console.log(`Request for ${req.path} took ${req.elapsedTime}`);
});

server.on('response', function (req, res, err, file, stat) {
  // Note: the response has already been sent at this point
  if (err) {
    console.error(`Error serving ${req.path}: ${err.message}`);
  } else if (file) {
    console.log(`Served ${file} with status ${res.status}`);
  }
});

view raw JSON →