koa2已发布了一段时间,能够考虑入手,参见Node.js最新Web技术栈(2016年4月)node
本文主要是koa 2的文档解读和runkoa介绍,让你们对koa 2有一个更简单直接的理解git
Koa requires node v4.0.0 or higher for (partial) ES2015 support.es6
部分特性须要ES2015,你们能够本身比对一下es6在node不一样版本里的支持特性github
http://kangax.github.io/compat-table/es6/express
const Koa = require('koa'); const app = new Koa(); // 此处开始堆叠各类中间件 //... app.use(ctx => { ctx.body = 'Hello Koa'; }); app.listen(3000);
注意注释部分,此处开始堆叠各类中间件npm
Koa 是一个 middleware framework, 它提供了 3 种不一样类型的中间件写法promise
中间件和express的中间件相似,是有顺序的,注意,大部分人都坑死在顺序上babel
下面以写一个logger中间件为例,一一阐明app
node sdk就支持的,就是最多见的koa
app.js
const Koa = require('koa'); const app = new Koa(); app.use((ctx, next) => { const start = new Date(); return next().then(() => { const ms = new Date() - start; console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); }); }); // response app.use(ctx => { ctx.body = 'Hello Koa in app.js'; }); app.listen(3000);
async/await是异步流程控制更好的解决方案,不少潮人都已经玩起来了,目前node sdk不支持,因此须要babel来转换一下
app-async.js
const Koa = require('koa'); const app = new Koa(); app.use(async (ctx, next) => { const start = new Date(); await next(); const ms = new Date() - start; console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); }); // response app.use(ctx => { ctx.body = 'Hello Koa in app-async.js'; }); app.listen(3000);
Generator是node 4(严格是0.12)开始支持的es6特性里的很是重要的一个,用generator和promise实现流程控制,让co充当执行器这一个角色,也是个不错的解决方案
千万别把generator叫成生成器,咱们通常习惯把scaffold叫成生成器
app-generator.js
const Koa = require('koa'); const app = new Koa(); const co = require('co'); app.use(co.wrap(function *(ctx, next) { const start = new Date(); yield next(); const ms = new Date() - start; console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); })); // response app.use(ctx => { ctx.body = 'Hello Koa in app-generator.js'; }); app.listen(3000);
启动执行
npm i -g runkoa runkoa app.js runkoa app-async.js runkoa app-generator.js
测试发起 http 请求
$ curl http://127.0.0.1:3000 Hello Koa in app.js
Old signature middleware (v1.x) support will be removed in v3
实际是koa核心包含了一个叫koa-convert的模块,它里面warning说,以generator做为中间件的写法将在koa@3里不支持
可是用co或koa-convert转过的仍是能够的,本文的3种写法都是长期支持的
这样写不行。。。。
// Koa will convert app.use(function *(next) { const start = new Date(); yield next; const ms = new Date() - start; console.log(`${this.method} ${this.url} - ${ms}ms`); });
这样写是能够的
const convert = require('koa-convert'); app.use(convert(function *(next) { const start = new Date(); yield next; const ms = new Date() - start; console.log(`${this.method} ${this.url} - ${ms}ms`); }));
我本人比较讨厌写babel,对于node sdk不支持的特性持观望态度,好比async/await这样的神器是能够用的,其余的是不必定必定要上的,那就观望好了
若是在koa 2里用到async/await就须要babel支持了
但是,我仍是不想用,就几行代码能搞定的事儿,我不想看到babel出如今个人代码里,因而就有了前面用到的runkoa,它的原理也是这样的,不过看起来更clean一些
Node.js 4.x和5.x支持的es特性仍是有很大差别的,若是不用到,还好,万一用到就只能babel去转换,还有就是async支持,必需要stage-3,那么也仍是须要babel。
Node.js sdk迟迟不更新很讨厌,babel更新太快也很讨厌
可是,不管从性能,仍是流程控制上,koa 2和它的后宫(中间件)都是很是好的解决方案