Koa 是一個相似於 Express 的Web開發框架,創始人也都是TJ。Koa 的主要特色是,使用了 ES6 的 Generator 函數,進行了架構的從新設計。Koa 的原理和內部結構很像 Express,可是語法和內部結構進行了升級。git
npm install --save koa
github
let koa = require('koa'); let app = koa(); app.use(function*(){ this.body = "hello xiaomo"; }); app.listen(8080);
如此這般咱們就建立了一個簡單的http服務器。這段程序的做用是監聽 8080 端口,當收到 GET 請求的時候,答覆 hello xiaomo
你應該注意到了,我沒有隻用 var 關鍵詞。我使用了 let 代替。在 ES6 中這基本上就是新的 var。這改變了變量的做用域,可是我不想在這裏多說。 express
另外一件事情有些奇怪,就是咱們使用關鍵詞 function*。這個星號表示這個函數是一個生成器函數。這意味着這個函數能夠在運行的時候跳出而後再跳回來。這個概念很難去表述,因此我給你舉個栗子。npm
function* inc () { let number = 0 while (true) yield number++ } let test = inc() console.log(test.next().value) // -> 0 console.log(test.next().value) // -> 1 console.log(test.next().value) // -> 2
我分解一下這個程序:服務器
inc 函數定義了一個生成器函數,在每一次 while 循環中,產出 number 變量而後 number 變量加 1
inc 函數被指派給了變量 test
inc 函數被迭代了 3 次,第一次的時候,number 變量在函數中被初始化了。而後,這個函數進入到了一個 while 循環,在以後的迭代中這個循環也不會退出。而後 number 0 被產出,因此這個能夠用 .value 方法接收。在後來的迭代中這個變量 number 自增了兩次。
我但願這能夠幫助理解一點生成器的工做原理。這只是很是複雜的 ES6 中的一小部分。架構
可是不管如何,讓咱們回到 koa。koa 很是簡單,甚至不包含一個路由。你須要在中間件生成器函數中手動作路由匹配:app
let koa = require('koa') let app = koa() // normal route app.use(function* (next) { if (this.path !== '/') { return yield next } this.body = 'hello world' }); // /404 route app.use(function* (next) { if (this.path !== '/404') { return yield next; } this.body = 'page not found' }); // /500 route app.use(function* (next) { if (this.path !== '/500') { return yield next; } this.body = 'internal server error' }); app.listen(8080)
你能夠看到,咱們只要用 if 就能夠作路由匹配了。你是否是很疑惑在這個上下文中的 this 是什麼,express 中的 req 和 res 去哪裏了。其實 this 綁定了大部分的 req 和 res 的函數和屬性。若是你想知道更多關於 this 的詳情,請點這裏。框架
讓咱們寫一個將請求中的內容大寫的中間件:koa
let koa = require('koa') let app = koa() app.use(upcaser()) function upcaser () { return function* (next) { yield next this.body = this.body.toUpperCase() } } app.listen(8080)