How to achieve the effect similar to express routing middleware?

  node.js, question

Nodejs’ event implementation is similar:

app.use(function (req, res, next) {
 cosole.log(res)
 next()
 })
 
 app.post(...)

Similar to the above, similar event effects need to be realized:

event.watch('all', cb)
 event.watch('[event type]', cb)

It is to monitor all events and give feedback without affecting the separate execution of the events. Use once and emit to create trigger events here

The following contents are mainly divided into two parts:

  1. Express middleware is roughly implemented.

  2. The subject is The Last Question.

First, express middleware is roughly implemented

Let’s talk about how express inside’s routing middleware is implemented. (In order to reduce complexity, the implementation of route splitting will not be discussed here.)

Routing add

  1. expressInternal maintenance of a system calledstackWhen the user calls a similarapp.post(path, fn)Such a route registration method, will go tostackInside adds a routing instance. This route instance is abstractly considered here to be{path: path, handler: fn}Of which,pathFor the path corresponding to the route,handlerFor the corresponding middleware.

  2. What is more special is thatapp.all(path, fn)In fact, the internal implementation is not complicated either. It can be roughly thought that it is to traverse all htp methods supported by node and then call the route registration method, such asapp.get(path, fn)app.post(path, fn)(Internal implementation is cleverer than this, not so rough)

Request processing

  1. The network requested it.expressThe http method and path of the request are detected internally and then traversed.stackArray, if satisfied at the same timeSame method and route hit, then the corresponding middleware is called.

  2. Same method and route hitThere may be more than one routing rule for, how do you implement multiple middleware calls in sequence? exactlynextAh! (Implementation)

Second, the main problem

Returning to the “event effect” in the question. With reference to the above steps, I basically know how to realize it.