lws-static: Static File Server Middleware
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
-
Error [ERR_REQUIRE_ESM]: require() of ES Module /path/to/node_modules/lws-static/index.js from /path/to/your/app.js not supported.
cause `lws-static` v3.0.0 and later are ESM-only modules, and you are attempting to import it using CommonJS `require()` syntax.fixUpdate your import statement from `const middleware = require('lws-static');` to `import middleware from 'lws-static';` and ensure your project is configured for ES modules (e.g., using `"type": "module"` in `package.json` or `.mjs` file extensions). -
TypeError: createStaticMiddleware is not a function
cause This typically occurs if the import path is incorrect, or if the imported symbol is not the default function that creates the middleware (e.g., a named import was used instead of the default export).fixEnsure you are using `import createStaticMiddleware from 'lws-static';` and that you are calling `createStaticMiddleware()` as a function when adding it to your `lws` stack, e.g., `stack: [createStaticMiddleware({ directory: './public' })]`. -
Error: ENOENT: no such file or directory, stat '/path/to/your/specified-directory'
cause The `directory` option provided to `lws-static` (either via CLI `--directory` or programmatically) points to a path that does not exist on the filesystem.fixDouble-check the `directory` path for typos or incorrect relative paths. Ensure the directory exists and that your application has the necessary read permissions. Consider using absolute paths with `path.join(__dirname, 'your-static-folder')` for robustness.
Warnings
- breaking `lws-static` versions 3.0.0 and above are ESM-only modules. Attempting to use `require()` will result in a runtime `ERR_REQUIRE_ESM` error.
- breaking The v3.0.0 release of `lws-static` raised its minimum requirements to Node.js v14 or higher and `local-web-server` (lws) v6 or higher, primarily due to the transition to ESM and updated internal dependencies.
- gotcha When configuring `lws-static` via the `lws` command-line interface, all options must be prefixed with `--static.`, e.g., `--static.maxage 3600`. Programmatic usage passes options directly to the middleware factory.
- gotcha `lws-static` relies on `koa-static` for its core functionality. While most options are passed through directly, in-depth understanding of `koa-static`'s behavior (e.g., how it handles URL rewriting or directory listings) can be crucial for complex configurations or debugging unexpected behavior.
Install
-
npm install lws-static -
yarn add lws-static -
pnpm add lws-static
Imports
- createStaticMiddleware
const createStaticMiddleware = require('lws-static');import createStaticMiddleware from 'lws-static';
- Lws
import Lws from 'local-web-server';
- StaticMiddlewareOptions
import type { Options } from 'lws-static';
Quickstart
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);
});
});