Node.js中的response.write失败

我正在试图制作一个代理服务器,例如从www.xxx.com获取一个页面,caching响应,然后将其发送到请求的浏览器。

为此,在服务器上创build一个请求来自xxx.com的页面的HTTP客户端。 响应以块(Buffers)的forms返回。 然后,由于块的数量根据网页的不同而不同,所以我把块放在一个缓冲区中。 然后我发送数组的元素。

我的问题不是所有的块都发送成功 。 有没有其他的方式可以caching数据发送之前? (我知道我可以直接发送数据,但是我需要发送caching,因为我想把它发送给多个浏览器)

为了保存我使用的块:

 function getURL(u) { u = url.parse(u); var client = http.createClient(u.port || 80, u.hostname); var request = client.request('GET', '/', { 'Host': u.hostname, }); var cache ={ }; cache.data = []; request.end(); request.on('response', function(response) { cache.statusCode = response.statusCode; cache.headers = response.headers; response.on('data', function(chunk) { cache.data.push(chunk); } } 

发送caching,我使用:

 function sendCache(response, cache) { var writeSuccess = []; response.writeHead(cache.statusCose, cache.headers); for (var i in cache.data) { // don't encode the data, leave it as it is writeSuccess[i] = response.write(cache.data[i], "binary"); console.log("chunk " + i + " is of length " + cache.data[i].length + ". Response success: " + writeSuccess[i]); } } 

在这里,我logging了response.write的返回值,以检查它是否成功。 在node.js API中,不会解释这个函数是否返回某个东西,但我只是试了一下。

我注意到,response.write有时是真的,然后为其他块的cachingfalse,而如果我直接发送没有caching的响应,所有块的response.write是真实的。

如果有人发现有什么问题,我正在做或者知道一个更好的方法来caching数据(最好是二进制的,这样所有的非ASCII字符都会被caching到)。

如果你想在node.js中代理请求,你应该尝试使用https://github.com/nodejitsu/node-http-proxy ,它会为你节省很多时间和头痛。

在最新版本的Node.js(v0.4.0)中,解决了从缓冲区写入响应的问题。 所以只要更新到这个版本,我的问题就解决了。

然而,人们必须知道response.write可能仍然是假的,但这并不意味着它不被发送,而不是直接发送(漏桶概念)。 这是我能从node.js库里的注释中得出的结论(我希望我是正确的)。