如何使用请求模块缓冲http响应?

我会转换一个传入的http响应,这是一个stream,并将数据存储在一个variables中。 我对节点stream没有太多的了解,我正在努力做到这一点。

var request = require('request'); request('http://google.com/doodle.png', function (error, response, body) { // buffer the stream response to and a string variable. }) 

UPDATE

这是我的完整代码。 我的目标是获取请求的图像,并将其存储在mongodb中。 但是图像总是被损坏。 我以为因为请求响应是一个stream,图像只被部分保存,因此腐败。

 request('http://google.com/doodle.png', function (error, response, body) { image = new Buffer(body, 'binary'); db.images.insert({ filename: 'google.png', imgData: image}, function (err) { // handle errors etc. }); }) 

现在你已经澄清了请求缓冲区的反应,我怎样才能妥善保存图像没有腐败的任何想法。

请求模块为您缓冲响应。 在callback中, body 一个string(或者Buffer )。

如果你没有提供callback,你只会从请求中获得一个stream。 request() 返回一个Stream

有关更多详细信息和示例,请参阅文档。


请求假定响应是文本,所以它会尝试将响应正文转换为sring(不pipeMIMEtypes)。 这会破坏二进制数据。 如果你想获得原始字节,指定一个null encoding

 request({url:'http://google.com/doodle.png', encoding:null}, function (error, response, body) { db.images.insert({ filename: 'google.png', imgData: body}, function (err) { // handle errors etc. }); }); 
 var options = { headers: { 'Content-Length': contentLength, 'Content-Type': 'application/octet-stream' }, url: 'http://localhost:3000/lottery/lt', body: formData, encoding: null, // make response body to Buffer. method: 'POST' }; 

将编码设置为null,返回Buffer。

你试过这个吗?

 request.get('http://google.com/doodle.png').pipe(request.put('{your mongo path}')) 

(尽pipeMongo不太了解Mongo知道它是否支持像这样的二进制数据的直接插入,但我知道CouchDB和Riak做的。