环境
nodejs: v0.12.7
koa: v0.21.0
koa 是这样介绍自己的
Koa 应用是一个包含中间件 generator 方法数组的对象。当请求到来时, 这些方法会以 stack-like 的顺序执行, 从这个角度来看,Koa 和其他中间件系统(比如 Ruby Rack 或者 Connect/Express )非常相似. 然而 Koa 的一大设计理念是: 通过其他底层中间件层提供高级「语法糖」,而不是Koa. 这大大提高了框架的互操作性和健壮性, 并让中间件开发变得简单有趣.
相比 express, koa 是一个非常精简的 web 框架,需要的中间件都可以自己造。koa 的 generator 委托的实现是基于 TJ 大神的 co。
测试代码-日志中间件:
var koa = require('koa');
var app = koa();
function logger() {
return function * (next) {
if ('/' != this.path) {
return;
}
var start = new Date;
yield next;
var ms = new Date - start;
console.log('URL:', this.url, " TIME:", ms, 'ms');
};
}
app.use(logger());
app.use(function * () {
this.body = 'hello koa';
});
app.listen(4000);
启动、访问
[root@nginx koa]# node --harmony app.js
URL: / TIME: 4 ms
测试代码-404中间件
var koa = require('koa');
var app = koa();
function pageNotFound() {
return function * (next) {
yield next;
if (404 != this.status) {
return;
}
this.status = 404;
switch (this.accepts('html', 'json')) {
case 'html':
this.type = 'html';
this.body = '<p>Page Not Found</p>';
break;
case 'json':
this.body = {
message: 'Page Not Found'
};
break;
default:
this.type = 'text';
this.body = 'Page Not Found';
}
}
}
app.use(pageNotFound());
app.use(function * () {
if ('/' == this.path) {
this.body = 'hello koa';
}
});
app.listen(4000);
使用 koa (其实是 co 的功劳),可以方便的将异步的回调的代码写成非阻塞的顺序的代码。
koa 例子