问题描述
我想将 HTTP 响应的内容流式传输到一个变量.我的目标是通过 request()
获取图像,并将其存储在 MongoDB 中 - 但图像总是已损坏.
I would like to stream the contents of an HTTP response to a variable. My goal is to get an image via request()
, and store it in in MongoDB - but the image is always corrupted.
这是我的代码:
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.
});
})
在这种情况下使用缓冲区/流的最佳方法是什么?
What is the best way to use Buffer/streams in this case?
推荐答案
请求模块为您缓冲响应.在回调中,body
是一个字符串(或).
The request module buffers the response for you. In the callback, body
is a string (or Buffer
).
如果你不提供回调,你只会从请求中得到一个流;request()
返回一个 Stream代码>
.
You only get a stream back from request if you don't provide a callback; request()
returns a Stream
.
request 假定响应是文本,因此它尝试将响应正文转换为 sring(无论 MIME 类型如何).这将损坏二进制数据.如果要获取原始字节,请指定 null
encoding
.
request assumes that the response is text, so it tries to convert the response body into a sring (regardless of the MIME type). This will corrupt binary data. If you want to get the raw bytes, specify a 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.
});
});
这篇关于如何使用请求模块缓冲 HTTP 响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!