lws-static: Static File Server Middleware

3.1.1 · active · verified Wed Apr 22

lws-static is a dedicated middleware plugin for the lws (local-web-server) ecosystem, designed to serve static files efficiently. It internally wraps koa-static, leveraging its robust capabilities for features like caching and directory indexing. The package is currently at version 3.1.1, actively maintained with periodic updates to its underlying dependencies, notably koa-static, and to ensure compatibility with the lws core framework. Its primary differentiator is seamless integration with lws's configuration system, allowing static file serving to be configured via concise CLI arguments or a programmatic lws setup. This approach simplifies the creation of development servers by offering a unified interface for defining the static root directory, cache control (max-age), request deferral, custom index files, and additional filename extensions, abstracting away direct koa-static configuration for lws users.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates programmatic setup of `lws` with `lws-static` to serve static files from a temporary directory. It configures caching, an index file, and proper cleanup.

import Lws from 'local-web-server';
import createStaticMiddleware from 'lws-static';
import path from 'path';
import fs from 'fs';

// Create a temporary directory and file for demonstration
const tempDir = path.join(process.cwd(), 'lws-public-temp');
const tempFile = path.join(tempDir, 'index.html');

// Ensure the directory exists and contains an index file
fs.mkdirSync(tempDir, { recursive: true });
fs.writeFileSync(tempFile, '<h1>Hello from lws-static!</h1>', 'utf8');

const lws = new Lws({
  port: 8080,
  stack: [
    createStaticMiddleware({
      directory: tempDir, // Serve from the temporary 'lws-public-temp' directory
      maxAge: 3600, // Cache for 1 hour (in seconds)
      index: 'index.html', // Default file if a directory is requested
      defer: true // Allow other downstream middleware to respond first
    })
  ]
});

lws.start();
console.log(`lws-static server running on http://localhost:8080`);
console.log(`Serving files from: ${tempDir}`);
console.log('Access http://localhost:8080 to see the static content.');
console.log('Press Ctrl+C to stop the server and clean up.');

// Clean up on exit
process.on('SIGINT', () => {
  console.log('\nStopping server and cleaning up...');
  lws.server.close(() => {
    if (fs.existsSync(tempDir)) {
      fs.rmSync(tempDir, { recursive: true, force: true });
      console.log('Temporary directory cleaned up.');
    }
    process.exit(0);
  });
});

view raw JSON →