我想将HTTP响应的内容流式传输到一个变量。我的目标是通过request()
获取图像,并将其存储在MongoDB中--但图像总是被损坏。
这是我的代码:
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.
});
})
在这种情况下,使用Buffer/streams的最佳方式是什么?
发布于 2014-12-07 11:22:10
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,返回缓冲区。
发布于 2013-01-04 04:15:41
你试过用管道传输这个吗?:
request.get('http://google.com/doodle.png').pipe(request.put('{your mongo path}'))
(虽然对Mongo还不够熟悉,不知道它是否支持像这样直接插入二进制数据,但我知道CouchDB和Riak支持。)
发布于 2018-09-11 17:24:08
现在,使用Node8、RequestJS和async await,您可以轻松地检索二进制文件。我使用了以下代码:
const buffer = await request.get(pdf.url, { encoding: null });
响应是一个包含pdf字节的缓冲区。比大的option对象和旧的skool回调干净得多。
https://stackoverflow.com/questions/14145533
复制相似问题