Helpers and API
Everything @routup/assets exports. The options are on Configuration.
assets()
Creates the plugin, which registers createHandler(directory, options) at the position of its app.use() call. It is also the default export.
declare function assets(
directory: string,
options?: OptionsInput,
): Plugin;assets() itself reads nothing: the scan of the directory starts when the plugin is registered with app.use(), and a plugin object registered twice scans twice.
createHandler()
Returns the handler the plugin registers, for app.use() without the plugin wrapper. The scan starts when it is called.
declare function createHandler(
directory: string,
options?: OptionsInput,
): Handler;createCoreHandler()
Returns the plain handler function, to call from a handler of your own, here to add a header to every served file. @routup/swagger-ui serves its UI files this way.
declare function createCoreHandler(
directory: string,
options?: OptionsInput,
): CoreHandler;import { fileURLToPath } from 'node:url';
import { App, defineCoreHandler } from 'routup';
import { createCoreHandler } from '@routup/assets';
export const app = new App();
const serveFile = createCoreHandler(fileURLToPath(new URL('public', import.meta.url)), { fallthrough: false });
app.use('/files', defineCoreHandler((event) => {
event.response.headers.set('x-robots-tag', 'noindex');
return serveFile(event);
}));Mount it with app.use(path, ...). The handler removes event.mountPath from the request path, and on a method route such as app.get('/download/:name', ...) that is the whole path, so every request gets the index file of the directory, or no file when there is none.
Types
| Type | Definition |
|---|---|
OptionsInput | The options of assets(), every key optional (Configuration) |
Options | The normalised options: every key but resolve set, patterns compiled to RegExp[], directoryPath absolute, plus fallbackPath |
ResolveFn | (event: IAppEvent) => Promise<unknown>, the type of resolve |
FileInfo | { stats: Stats, filePath: string }, one entry of the scanned list |
ReadDirectoryCallback | (relativePath: string, absolutePath: string, stats: Stats) => void |
Other Exports
Internal building blocks of the handler, exported by the package entry.
| Export | Description |
|---|---|
buildOptions | (input: OptionsInput) => Options: applies the defaults, compiles the patterns, resolves the directory against the working directory |
scanFiles | (stack: Record<string, FileInfo>, options: Options) => Promise<void>: fills stack with the files of options.directoryPath, keyed by path; does nothing when scan is false |
readDirectory | (dir: string, callback: ReadDirectoryCallback, prefix?: string) => Promise<void>: walks a directory recursively and calls callback per file, with prefix (default '') joined before each relative path; skips entries that vanish or dangle during the walk |
isRegexMatch | (input: string, pattern: RegExp | RegExp[]) => boolean: true when any pattern matches |