Home > Web Front-end > JS Tutorial > Compare the differences and connections between express and koa middleware patterns

Compare the differences and connections between express and koa middleware patterns

巴扎黑
Release: 2017-08-11 10:08:57
Original
2626 people have browsed it

This article mainly introduces the detailed comparison between express and koa middleware modes. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.

Cause

I’ve recently been learning how to use koa. Since koa is a fairly basic web framework, a complete web application is Most of the required things are introduced in the form of middleware, such as koa-router, koa-view, etc. It is mentioned in the koa documentation: koa's middleware model is different from express's. koa is an onion type, express is a linear type. As for why this is the case, many articles on the Internet do not specifically analyze it. Or simply put, it is the characteristics of async/await. Let’s not talk about whether this statement is right or wrong. For me, this statement is still too vague. So I decided to analyze the similarities and differences in the principles and usage of the two middleware implementations through the source code.

For the sake of simplicity, express here is replaced by connect (the implementation principle is the same)

Usage

Both are based on the official website (github) document Subject to

connect

The following is the usage on the official website:


var connect = require('connect');
var http = require('http');

var app = connect();

// gzip/deflate outgoing responses
var compression = require('compression');
app.use(compression());

// store session state in browser cookie
var cookieSession = require('cookie-session');
app.use(cookieSession({
 keys: ['secret1', 'secret2']
}));

// parse urlencoded request bodies into req.body
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false}));

// respond to all requests
app.use(function(req, res){
 res.end('Hello from Connect!\n');
});

//create node.js http server and listen on port
http.createServer(app).listen(3000);
Copy after login

According to the document we can see, connect provides a simple routing function:


app.use('/foo', function fooMiddleware(req, res, next) {
 // req.url starts with "/foo"
 next();
});
app.use('/bar', function barMiddleware(req, res, next) {
 // req.url starts with "/bar"
 next();
});
Copy after login

The middleware of connect is linear. After next, continue to search for the next middleware. This mode is also intuitively good. Understand that middleware is a series of arrays, and the processing method for finding corresponding routes through route matching is middleware. In fact, connect is also implemented in this way.

app.use is to insert new middleware into the middleware array. The execution of middleware relies on the private method app.handle for processing, and the same principle applies to express.

koa

Compared with connect, koa’s middleware model is not so intuitive. Let’s use the diagram on the Internet to express it:

That is, koa will come back after processing the middleware, which gives us more room for operation. Let’s take a look at koa’s official website example:


const Koa = require('koa');
const app = new Koa();

// x-response-time

app.use(async (ctx, next) => {
 const start = Date.now();
 await next();
 const ms = Date.now() - start;
 ctx.set('X-Response-Time', `${ms}ms`);
});

// logger

app.use(async (ctx, next) => {
 const start = Date.now();
 await next();
 const ms = Date.now() - start;
 console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});

// response

app.use(async ctx => {
 ctx.body = 'Hello World';
});

app.listen(3000);
Copy after login

Obviously, when koa processing middleware encounters await next(), it will pause the current middleware and process the next middleware, and finally go back to continue processing the remaining tasks. Although it is very complicated to say, But intuitively we have a vaguely familiar feeling: isn't it just a callback function? Let’s not talk about the specific implementation method here, but it is indeed a callback function. It has nothing to do with the features of async/await.

Source code brief analysis

The core difference between connect and koa middleware mode lies in the implementation of next. Let us briefly look at the implementation of next between the two.

connect

The source code of connect is quite small and only contains 200 lines of comments. It seems very clear that the connect middleware processing lies in the private method proto.handle. , the same next is also implemented here


// 中间件索引
var index = 0
function next(err) {


 // 递增
 var layer = stack[index++];

 // 交由其他部分处理
 if (!layer) {
  defer(done, err);
  return;
 }

 // route data
 var path = parseUrl(req).pathname || '/';
 var route = layer.route;

 // 递归
 // skip this layer if the route doesn't match
 if (path.toLowerCase().substr(0, route.length) !== route.toLowerCase()) {
  return next(err);
 }

 // call the layer handle
 call(layer.handle, route, err, req, res, next);
 }
Copy after login

After deleting the obfuscated code, we can see that the next implementation is also very simple. A recursive call sequence looking for middleware. Keep calling next. The code is quite simple but the idea is worth learning.

Where done is the third-party processing method. Other parts dealing with sub apps and routing have been deleted. Not the point

koa

koa separates the implementation of next into a separate package. The code is simpler, but it implements a seemingly more complex function


function compose (middleware) {
 return function (context, next) {
 // last called middleware #
 let index = -1
 return dispatch(0)
 function dispatch (i) {
  index = i
  try {
  return Promise.resolve(fn(context, function next () {
   return dispatch(i + 1)
  }))
  } catch (err) {
  return Promise.reject(err)
  }
 }
 }
}
Copy after login

Looking at the code processed above, some students may still be confused.

Then let’s continue processing:


function compose (middleware) {

 return function (context, next) {
 // last called middleware #
 let index = -1
 return dispatch(0)
 function dispatch (i) {
  index = i
  let fn = middleware[i]
  if (i === middleware.length) {
  fn = next
  }
  if (!fn) return
  return fn(context, function next () {
  return dispatch(i + 1)
  })
 }
 }
}
Copy after login

In this way, the program is simpler and has nothing to do with async/await. Let’s take a look at the results. Okay


var ms = [
 function foo (ctx, next) {
 console.log('foo1')
 next()
 console.log('foo2')
 },
 function bar (ctx, next) {
 console.log('bar1')
 next()
 console.log('bar2')
 },
 function qux (ctx, next) {
 console.log('qux1')
 next()
 console.log('qux2')
 }
]

compose(ms)()
Copy after login

Execute the above program and we can find the output in sequence:

foo1
bar1
qux1
qux2
bar2
foo2

is also the so-called onion model of koa. At this point we can draw the conclusion that koa's middleware model has no actual connection with async or generator, but koa emphasizes async takes precedence. The so-called middleware pause is only due to the callback function (in my opinion, there is no difference between promise.then and callback, and even async/await is also a form of callback).

The above is the detailed content of Compare the differences and connections between express and koa middleware patterns. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template