Skip to content

Commit

Permalink
support extname options
Browse files Browse the repository at this point in the history
  • Loading branch information
vicanso committed Sep 25, 2016
1 parent bd011d4 commit 4c5016a
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 18 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ app.use(serve(staticPath, {
etag: false,
lastModified: false,
'404': 'next',
extname: ['.html'],
}));
const port = process.env.PORT || 10000;
app.listen(port);
Expand Down Expand Up @@ -68,6 +69,8 @@ console.dir('server listen on:' + port);

- `404` Set not found handler. If set 'next', it will call next when not found, otherwise will throw an error (404).

- `extname` Set default extname.

## License

MIT
59 changes: 43 additions & 16 deletions lib/serve.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,51 @@ const path = require('path');
const fs = require('fs');
const etag = require('etag');
const mime = require('mime');
const util = require('util');

const statsPromise = (file) => new Promise(resolve => fs.stat(file, (err, stat) => {
if (err) {
resolve(null);
} else {
resolve(stat);
}
}));

/**
* [exists description]
* @param {[type]} file [description]
* @return {[type]} [description]
*/
function exists(file) {
return new Promise((resolve, reject) => {
fs.stat(file, (e, stat) => {
if (e) {
const err = e;
err.status = 404;
reject(err);
} else if (stat.isDirectory()) {
const err = new Error('The path is directory');
err.status = 404;
reject(err);
} else {
resolve(stat);
function exists(file, extnameList) {
const fns = [];
const extname = path.extname(file);
fns.push(statsPromise(file));
if (!extname && extnameList && extnameList.length) {
extnameList.forEach(ext => {
fns.push(statsPromise(`${file}${ext}`));
});
}
return Promise.all(fns).then(arr => {
let stats = null;
let index = -1;
arr.forEach((item, i) => {
if (!stats && item) {
stats = item;
index = i;
}
});
if (!stats) {
const err = new Error('The file is not exists.');
err.status = 404;
throw err;
}
if (stats.isDirectory()) {
const err = new Error('The file is directory');
err.status = 404;
throw err;
}
stats.extname = extnameList[index - 1];
return stats;
});
}

Expand All @@ -38,6 +62,7 @@ function serve(staticPath, options) {
const opts = Object.assign({
etag: true,
lastModified: true,
extname: ['.html', '.htm'],
}, options);
debug('static path:%s, opts:%j', staticPath, opts);
if (options && (options.disableETag || options.disableLastModified)) {
Expand All @@ -51,6 +76,7 @@ function serve(staticPath, options) {
const accessList = ['allow', 'deny', 'ignore'];
const denyQuerystring = opts.denyQuerystring;
const defaultCharset = opts.charset || 'utf-8';
const extnameList = util.isArray(opts.extname) ? opts.extname : [opts.extname];
opts.dotfiles = accessList.indexOf(opts.dotfiles) === -1 ? 'ignore' : opts.dotfiles;

return (ctx, next) => {
Expand All @@ -77,8 +103,9 @@ function serve(staticPath, options) {
return ctx.throw(404);
}

return exists(file).then((stats) => {
const type = mime.lookup(file);
return exists(file, extnameList).then((stats) => {
const foundFile = `${file}${stats.extname || ''}`;
const type = mime.lookup(foundFile);
const charset = mime.charsets.lookup(type) || defaultCharset;
const headers = Object.assign({}, defaultHeaders);
if (opts.etag) {
Expand All @@ -101,7 +128,7 @@ function serve(staticPath, options) {
ctx.remove('Content-Length');
} else {
/* eslint no-param-reassign:0 */
ctx.body = fs.createReadStream(file);
ctx.body = fs.createReadStream(foundFile);
}
return next();
}).catch(err => {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "koa-static-serve",
"description": "static serve middlware for koa",
"version": "2.1.0",
"version": "2.1.1",
"author": "Tree Xie <vicansocanbico@gmail.com>",
"keywords": [
"koa",
Expand Down
11 changes: 10 additions & 1 deletion test/serve.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ describe('serve', function() {
.expect(404, done);
});

it('should go next whe get file not exists', done => {
it('should go next when get file not exists', done => {
const app = new Koa();

app.use(serve(assets, {
Expand All @@ -60,6 +60,15 @@ describe('serve', function() {
.expect(404, done);
});

it('should add default ext successful', done => {
const app = new Koa();

app.use(serve(assets));
request(app.listen())
.get('/index')
.expect(200, done);
});

it('should get dotfiles successful', done => {
const app = new Koa();

Expand Down

0 comments on commit 4c5016a

Please sign in to comment.