node from koa then to express to the development koa2

koa Express is the next generation of web-based Node.js framework, there are two versions 1.x and 2.0.

history

1. Express

Express is the first generation of the most popular web framework, it is Node.js http the package, together with the following:

'use strict'

var express=require('express');
var app=express();

app.get('/',function(req,res){
    res.send('Hello world!');
});

app.listen(3000,function(){
    console.log('Example app listening on port 3000!');
});

//可以在http://127.0.0.1:3000访问

Although the Express API is very simple, but it is based on grammar ES5, to achieve asynchronous code, only one way: callback. If the asynchronous nesting level too, to write code is very ugly:

Although you can use this library to organize async asynchronous code, but with asynchronous callback writing is so painful!

2. 1.0

With the start of the new version of Node.js support ES6, Express team has re-written the next generation of web-based generator ES6 the framework koa. Express and compared, koa 1.0 using asynchronous generator, the synchronization code looks like:

var KOA = the require ( 'KOA' );
 var App = KOA (); 

app.use ( '/ Test', function * () { 
    the yield doReadFile1 (); 
    var Data = the yield doReadFile2 ();
     the this .body = Data; 
}); 

app.listen ( 3000 );
 // can be accessed http://127.0.0.1:3000

Asynchronous generator with a lot more than a simple correction, but the intention is not asynchronous generator. Promise is asynchronous design, but the wording ...... Promise think about the complex. To simplify asynchronous code, ES7 (currently a draft, not yet released) introduces new keywords asyncand awaitcan easily put a function becomes asynchronous mode:

async function () {
    var data = await fs.read('/file1');
}

This is the future standard asynchronous JavaScript code, very simple, and easy to use.

3. koa2

koa team did not stop at the koa 1.0, they are very advanced based ES7 developed koa2, and koa 1 compared, koa2 Promise and with full use asyncto implement asynchronous.

koa2 code looks like this:

app.use(async (ctx, next) => {
    await next();
    var data = await doReadFile();
    ctx.response.type = 'text/plain';
    ctx.response.body = data;
});

For compatibility reasons, the current generator koa2 still supported the wording, but the next version will be removed.

koa2 is the future trend

 

Guess you like

Origin www.cnblogs.com/fqh123/p/11032446.html