Home  >  Q&A  >  body text

node.js - 怎么实现类似express路由中间件的效果?

nodejs的事件实现类似:

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

app.post(...)

类似上面,需要实现类似的事件效果:

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

就是监控所有事件并作出反馈但不会影响事件的单独执行。这里使用once和emit创建触发事件

迷茫迷茫2766 days ago664

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 14:52:20

    The following content is mainly divided into two parts:

    1. Express middleware is roughly implemented.

    2. The subject’s last question.

    1. Rough implementation of express middleware

    First, let’s briefly talk about how the routing middleware in express is implemented. (In order to reduce complexity, we will not talk about the implementation of route splitting here)

    Route added

    1. express internally maintains a data called stack. When the user calls a route registration method like app.post(path, fn), a route instance will be added to stack. Abstractly, this routing instance is considered here as {path: path, handler: fn}, where path is the path corresponding to the route, and handler is the corresponding middleware.

    2. is more special than app.all(path, fn). In fact, the internal implementation is not complicated. It can be roughly thought of as traversing all htp methods supported by node, and then calling the route registration method, such as app.get(path, fn), app.post(path, fn) ...(The internal implementation is more clever than this, not so crude)

    Request processing

    1. When a network request comes in, express will internally detect the http method and path of the request, and then traverse the stack array. If method相同 且 路由命中 is satisfied at the same time, then the corresponding middleware will be called.

    2. There may be multiple routing rules for
    3. method相同 且 路由命中, so how do you implement the sequential invocation of multiple middlewares? That’s it next. (Implementation omitted)

    2. Topic question

    Back to the "event effect" in the question. Refer to the above steps and you will basically know how to implement it.

    reply
    0
  • Cancelreply