Lws Directory Listing Middleware

3.1.1 · active · verified Wed Apr 22

lws-index is a middleware plugin designed for the Lightweight Web Server (lws) ecosystem, enabling the serving of directory listings. It functions as a wrapper around the popular `serve-index` library, integrating its capabilities seamlessly into lws. The current stable version is 3.1.1, and being part of the lws family, it generally follows the lws release cadence, focusing on stability and compatibility within that ecosystem. Its key differentiator is its straightforward integration as a plugin for lws, providing configurable options like specifying a root directory, showing hidden files, and choosing between 'tiles' or 'details' view modes, without needing manual Express.js-style middleware setup. It is often used in conjunction with `lws-static` for comprehensive file serving.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up `lws` programmatically, configuring it with both `lws-static` to serve files and `lws-index` to provide directory listings. It creates a sample directory structure and starts a server that will show directory contents when navigating to a folder.

import Lws from 'lws';
import lwsIndex from 'lws-index';
import lwsStatic from 'lws-static';
import { createRequire } from 'module';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const require = createRequire(import.meta.url);

// Ensure a directory exists for testing
import { mkdirSync, writeFileSync } from 'fs';
const publicDir = path.join(__dirname, 'public');
mkdirSync(publicDir, { recursive: true });
writeFileSync(path.join(publicDir, 'index.html'), '<h1>Hello from Lws!</h1>');
mkdirSync(path.join(publicDir, 'subfolder'), { recursive: true });
writeFileSync(path.join(publicDir, 'subfolder', 'test.txt'), 'This is a test file.');
writeFileSync(path.join(publicDir, '.hiddenfile'), 'You should not see this by default.');

const PORT = process.env.PORT || 8000;

new Lws().listen({
  port: PORT,
  directory: publicDir, // This sets the default root for lws-static and lws-index
  stack: [
    lwsStatic(), // Serve static files first
    lwsIndex({
      root: publicDir, // Explicitly set the root for the index listing
      hidden: false,  // Do not show hidden files by default
      view: 'tiles'   // Use the 'tiles' display mode
    })
  ]
}).on('started', ({ url }) => {
  console.log(`Lws server with directory listing started on ${url}`);
  console.log(`Try navigating to ${url}/subfolder/`);
});

view raw JSON →