A module for serving static files with etags, caching, gzip compression, CORS support, and directory indexing.
—
The main st() factory function and Mount class provide the core static file serving functionality with multiple configuration options and request handling capabilities.
Creates a configured request handler function for serving static files.
/**
* Creates a static file server handler
* @param path - Filesystem path to serve files from (required)
* @returns Request handler function
*/
function st(path: string): RequestHandler;
/**
* Creates a static file server handler with URL mount point
* @param path - Filesystem path to serve files from (required)
* @param url - URL mount point (default: '/')
* @returns Request handler function
*/
function st(path: string, url: string): RequestHandler;
/**
* Creates a static file server handler with full options
* @param path - Filesystem path to serve files from (required)
* @param url - URL mount point (default: '/')
* @param options - Configuration options
* @returns Request handler function
*/
function st(path: string, url: string, options: StOptions): RequestHandler;
/**
* Creates a static file server handler from options object
* @param options - Configuration options including path
* @returns Request handler function
*/
function st(options: StOptions): RequestHandler;
interface RequestHandler {
/** Request handler function - returns true if request was handled */
(req: http.IncomingMessage, res: http.ServerResponse, next?: Function): boolean;
/** Access to underlying Mount instance */
_this: Mount;
}Usage Examples:
const st = require('st');
const http = require('http');
// Simple path-only usage
const handler1 = st('./public');
// With URL mount point
const handler2 = st('./static', '/static');
// With full options
const handler3 = st('./assets', '/assets', {
cache: true,
gzip: true,
cors: true
});
// Options object approach
const handler4 = st({
path: './files',
url: '/files',
index: 'index.html',
dot: false
});
// Using with HTTP server
http.createServer((req, res) => {
if (handler4(req, res)) {
return; // st handled the request
}
res.statusCode = 404;
res.end('Not Found');
}).listen(3000);
// Using with Express-style middleware
http.createServer((req, res) => {
handler4(req, res, () => {
res.end('Not a static file');
});
}).listen(3001);Internal Mount class that handles the actual file serving logic. Exposed for advanced usage scenarios.
/**
* Mount class constructor - creates a new mount instance
* @param options - Configuration options (must include path)
* @throws Error if no options provided or invalid options
*/
class Mount {
constructor(options: StOptions);
}Usage Example:
const { Mount } = require('st');
const mount = new Mount({
path: './public',
url: '/public',
cache: true
});
// Access mount properties
console.log(mount.path); // Resolved filesystem path
console.log(mount.url); // URL mount point
console.log(mount.opt); // Original optionsThe main request handling method of the Mount class.
/**
* Handles HTTP requests for static files
* @param req - HTTP request object
* @param res - HTTP response object
* @param next - Optional callback for unhandled requests (Express-style)
* @returns true if request was handled, false otherwise
*/
serve(req: http.IncomingMessage, res: http.ServerResponse, next?: Function): boolean;Usage Example:
const mount = new Mount({ path: './static' });
http.createServer((req, res) => {
const handled = mount.serve(req, res, () => {
res.statusCode = 404;
res.end('Not found');
});
if (!handled) {
console.log('Request not handled by st');
}
}).listen(3000);Utility methods for converting between filesystem paths and URLs.
/**
* Extracts path component from URI with security checks
* @param url - Request URL to process
* @returns Processed path string, 403 for forbidden paths, or false for invalid URLs
*/
getUriPath(url: string): string | number | false;
/**
* Converts URL path to filesystem path
* @param uriPath - URI path component (from getUriPath)
* @returns Absolute filesystem path
*/
getPath(uriPath: string): string;
/**
* Converts filesystem path to URL
* @param filePath - Absolute filesystem path
* @returns URL path or false if path is outside served directory
*/
getUrl(filePath: string): string | false;Usage Example:
const mount = new Mount({ path: '/var/www', url: '/static' });
// Extract and validate URI path
const uriPath = mount.getUriPath('/static/images/logo.png');
if (uriPath === 403) {
console.log('Security violation detected');
} else if (uriPath === false) {
console.log('Invalid URL');
} else {
// Convert to filesystem path
const fsPath = mount.getPath(uriPath);
console.log(fsPath); // '/var/www/images/logo.png'
// Convert back to URL
const url = mount.getUrl(fsPath);
console.log(url); // '/static/images/logo.png'
}Built-in error handling with appropriate HTTP status codes.
/**
* Handles errors and sends appropriate HTTP responses
* @param error - Error object or HTTP status code number
* @param res - HTTP response object
*/
error(error: Error | number, res: http.ServerResponse): void;Error Codes:
404: File not found (ENOENT, EISDIR errors)403: Forbidden (EPERM, EACCES errors, dot files, path traversal)500: Server error (other errors)Methods for handling directory requests and auto-indexing.
/**
* Handles directory requests - serves index file or generates directory listing
* @param path - Filesystem directory path
* @param req - HTTP request object
* @param res - HTTP response object
*/
index(path: string, req: http.IncomingMessage, res: http.ServerResponse): void;
/**
* Generates HTML directory listing
* @param path - Filesystem directory path
* @param req - HTTP request object
* @param res - HTTP response object
*/
autoindex(path: string, req: http.IncomingMessage, res: http.ServerResponse): void;Methods for serving individual files with caching and compression.
/**
* Serves individual files - determines whether to use cache or streaming
* @param path - Filesystem file path
* @param fd - File descriptor
* @param stat - File stats object
* @param etag - Generated ETag for the file
* @param req - HTTP request object
* @param res - HTTP response object
* @param end - Cleanup function for file descriptor
*/
file(path: string, fd: number, stat: fs.Stats, etag: string, req: http.IncomingMessage, res: http.ServerResponse, end: Function): void;
/**
* Serves files from memory cache
* @param path - Filesystem file path
* @param stat - File stats object
* @param etag - Generated ETag for the file
* @param req - HTTP request object
* @param res - HTTP response object
*/
cachedFile(path: string, stat: fs.Stats, etag: string, req: http.IncomingMessage, res: http.ServerResponse): void;
/**
* Streams files from filesystem with optional compression and caching
* @param path - Filesystem file path
* @param fd - File descriptor
* @param stat - File stats object
* @param etag - Generated ETag for the file
* @param req - HTTP request object
* @param res - HTTP response object
* @param end - Cleanup function for file descriptor
*/
streamFile(path: string, fd: number, stat: fs.Stats, etag: string, req: http.IncomingMessage, res: http.ServerResponse, end: Function): void;Internal methods used by the caching system to load data into various caches.
/**
* Loads file statistics into the stat cache
* @param key - Cache key (either 'fd:path' or just path)
* @param callback - Callback function (err, stat)
*/
_loadStat(key: string, callback: (err: Error | null, stat?: fs.Stats) => void): void;
/**
* Loads directory index HTML into the index cache
* @param path - Directory filesystem path
* @param callback - Callback function (err, html)
*/
_loadIndex(path: string, callback: (err: Error | null, html?: Buffer) => void): void;
/**
* Loads directory listing into the readdir cache
* @param path - Directory filesystem path
* @param callback - Callback function (err, data)
*/
_loadReaddir(path: string, callback: (err: Error | null, data?: object) => void): void;
/**
* Content loading method - should never be called as content is loaded via streaming
* @param key - Cache key (unused)
* @param callback - Callback function that returns an error
*/
_loadContent(key: string, callback: (err: Error) => void): void;Static utility functions used internally by the st module.
/**
* Generates ETag from file stats
* @param stat - File stats object
* @returns ETag string in format "dev-ino-mtime"
*/
function getEtag(stat: fs.Stats): string;
/**
* Determines if gzip compression should be used for a request
* @param path - File path
* @param req - HTTP request object
* @returns true if gzip should be used
*/
function getGz(path: string, req: http.IncomingMessage): boolean;Install with Tessl CLI
npx tessl i tessl/npm-st