koa-files

A static files serving middleware for koa.

Usage no npm install needed!

<script type="module">
  import koaFiles from 'https://cdn.skypack.dev/koa-files';
</script>

README

koa-files

A static files serving middleware for koa.

NPM Version Download Status Snyk Vulnerabilities Node Version Dependencies

Installation

$ npm install koa-files

API

const Koa = require('koa');
const server = require('koa-files');

const app = new Koa();

// Static files server
app.use(server(root, options));
  • root root directory string. nothing above this root directory can be served.
  • options options object.

Options

acceptRanges?: boolean

  • Enable or disable accepting ranged requests. Disabling this will not send Accept-Ranges and ignore the contents of the Range request header. defaults to true.

cacheControl?: string

etag?: boolean

  • Enable or disable etag generation, defaults to true.

lastModified?: boolean

  • Enable or disable Last-Modified header, defaults to true. Uses the file system's last modified value. defaults to true.

ignore?: (path: string) => boolean

  • Set ignore rules. defaults to undefined.

defer?: boolean

  • If true, serves after await next(), allowing any downstream middleware to respond first. defaults to false.

Example

/**
 * @module server
 * @license MIT
 * @author nuintun
 */

'use strict';

const Koa = require('koa');
const server = require('koa-files');

const app = new Koa();
const port = process.env.PORT || 80;

/**
 * @function httpError
 * @param {NodeJS.ErrnoException} error
 * @returns {boolean}
 */
function httpError(error) {
  return /^(EOF|EPIPE|ECANCELED|ECONNRESET|ECONNABORTED)$/i.test(error.code);
}

// Static files server
app.use(server('tests', { cacheControl: 'public, max-age=31557600' }));

// Listen error event
app.on('error', error => !httpError(error) && console.error(error));

// Start server
app.listen(port, () => console.log(`> server running at: 127.0.0.1:${port}`));

Features

Support multipart range and download resumption.

License

MIT