UNPKG

916 BJavaScriptView Raw
1
2/**
3 * Module dependencies.
4 */
5
6var assert = require('assert');
7var debug = require('debug')('koa-static');
8var send = require('koa-send');
9
10/**
11 * Expose `serve()`.
12 */
13
14module.exports = serve;
15
16/**
17 * Serve static files from `root`.
18 *
19 * @param {String} root
20 * @param {Object} [opts]
21 * @return {Function}
22 * @api public
23 */
24
25function serve(root, opts) {
26 opts = opts || {};
27
28 assert(root, 'root directory is required to serve files');
29
30 // options
31 debug('static "%s" %j', root, opts);
32 opts.root = root;
33 opts.index = opts.index || 'index.html';
34
35 if (!opts.defer) {
36 return function *(next){
37 if (this.idempotent && (yield send(this, this.path, opts))) return;
38 yield next;
39 }
40 }
41
42 return function *(next){
43 yield next;
44
45 // response is already handled
46 if (!this.idempotent || this.body != null || this.status != null) return;
47
48 yield send(this, this.path, opts);
49 }
50}
\No newline at end of file