lws-range: HTTP Range Request Middleware for lws

4.0.1 · active · verified Wed Apr 22

This package, `lws-range`, is a middleware plugin designed for the `local-web-server` (`lws`) ecosystem, specifically adding robust support for HTTP Range Requests. It effectively wraps the `koa-range` library to integrate this functionality seamlessly into `lws` servers. As of version 4.0.1, it provides compliant handling of partial content requests, enabling clients to request specific byte ranges of a resource, which is crucial for features like video streaming, large file downloads with resume capabilities, and efficient caching. The project appears to be actively maintained, indicated by recent version releases and continuous integration. Its primary differentiator is its deep integration with the `lws` server, providing a simple `--stack` activation for this common HTTP feature without needing to manually configure low-level range request parsing. It mandates Node.js version 12.17 or higher.

Common errors

Warnings

Install

Imports

Quickstart

Sets up an `lws` server programmatically with `lws-range` and `lws-static` middleware, demonstrating how to enable HTTP Range Request support for static files. Includes setup for a test file.

import lws from 'lws';
import lwsRange from 'lws-range';
import lwsStatic from 'lws-static'; // Assuming lws-static is also installed
import { resolve } from 'path';
import { writeFileSync, mkdirSync } from 'fs';

const publicDir = resolve(__dirname, './public');
mkdirSync(publicDir, { recursive: true });

// Create a sample large file for testing range requests
const largeFilePath = resolve(publicDir, 'large-file.txt');
const dummyContent = 'This is a sample text file to demonstrate HTTP Range requests. '.
  repeat(100) + 'It should be sufficiently long to make range requests meaningful.';
writeFileSync(largeFilePath, dummyContent);

// Create a simple lws server with range request support and static file serving
const server = lws.create({
  // The middleware stack defines the order of processing
  stack: [
    // lws-range must come before lws-static to handle range requests for static files
    lwsRange(), 
    lwsStatic({ 
      root: publicDir, // Serve files from the 'public' directory
      index: ['index.html', 'index.htm'] // Specify default index files
    })
  ],
  port: process.env.PORT ?? 8000 // Listen on port 8000 or specified by env var
});

server.listen(server.port, () => {
  console.log(`lws server with range support listening on http://localhost:${server.port}`);
  console.log('To test, create a file named ' + largeFilePath + ' (or use the one created by this script).');
  console.log('Then try sending a curl request with a Range header, e.g.,');
  console.log(`curl -I -H "Range: bytes=0-100" http://localhost:${server.port}/large-file.txt`);
  console.log(`curl -H "Range: bytes=0-10" http://localhost:${server.port}/large-file.txt`);
});

view raw JSON →