NodeJS middleware how to read from a writable stre

2019-09-06 23:55发布

I'm working on a app (using Connect not Express) composed of a set of middlewares plus node-http-proxy module, that is, I have a chain of middlewares like:

midA -> midB -> http-proxy -> midC 

In this scenario, the response is wrote by the http-proxy that proxies the request to some target and returns the content.

I would like to create a middleware (say midB) to act as a cache. The idea is:

  • If url is cached the cache-middleware writes the response and avoids continuing the middleares chain.
  • If url is not cached the cache-middleware passes the request within the middlewares chain bit requires to read the final response content to be cached.

How can achieve this? Or there is another approach?

Cheers

1条回答
Lonely孤独者°
2楼-- · 2019-09-07 00:16

Answering myself. If you have a middleware like function(req, res, next){..} and need to read the content of the response object.

In this case the res is a http.ServerResponse object, a writable stream where every middleware in the chain is allowed to write content that will conform the response we want to return.

Do not confuse with the response you get when make a request with http.request(), that is a http.IncomingMessage which in fact is a readable stream.

The way I found to read the content all middlewares write to the response is redefining the write method:

var middleare = function(req, res, next) {

  var data = "";
  res._oldWrite = res.write;
  res.write = function(chunk, encoding, cb) {
    data += chunck;
    return res._oldWrite.call(res, chunck, encoding, cb);
  }

  ...
}

Any other solutions will be appreciated.

查看更多
登录 后发表回答