NodeJS中间件如何从可写流中读取(http.ServerResponse) [英] NodeJS middleware how to read from a writable stream (http.ServerResponse)
问题描述
我正在开发由一组中间件和node-http-proxy模块组成的应用程序(使用Connect not Express ),也就是说,我有一系列中间件,例如:>
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
在这种情况下,响应是由http-proxy编写的,该代理将请求代理到某个目标并返回内容.
In this scenario, the response is wrote by the http-proxy that proxies the request to some target and returns the content.
我想创建一个中间件(例如midB
)充当缓存.这个想法是:
I would like to create a middleware (say midB
) to act as a cache. The idea is:
- 如果缓存了url,则缓存中间件将写入响应,并避免继续使用Middleares链.
- 如果未缓存url,则缓存中间件将中间件链中的请求传递给位,要求读取要缓存的最终响应内容.
如何实现呢?还是有另一种方法?
How can achieve this? Or there is another approach?
欢呼
推荐答案
正在回答自己.
如果您有像function(req, res, next){..}
这样的中间件,并且需要读取响应对象的内容.
Answering myself.
If you have a middleware like function(req, res, next){..}
and need to read the content of the response object.
在这种情况下,res
是一个http.ServerResponse
对象,这是一个可写流,其中链中的每个中间件都可以编写符合我们要返回的响应的内容.
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.
在与
http.request()
进行请求时,不要混淆您得到的响应,这是一个http.IncomingMessage
实际上是可读的流.
Do not confuse with the response you get when make a request with
http.request()
, that is ahttp.IncomingMessage
which in fact is a readable stream.
我发现读取所有中间件写入响应的内容的方式是重新定义write
方法:
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.
这篇关于NodeJS中间件如何从可写流中读取(http.ServerResponse)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!