node.js 如何使用请求模块缓冲 HTTP 响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14145533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to buffer an HTTP response using the request module?
提问by jamjam
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.
我想将 HTTP 响应的内容流式传输到变量。我的目标是通过 获取图像request(),并将其存储在 MongoDB 中 - 但图像总是损坏。
This is my code:
这是我的代码:
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?
在这种情况下使用缓冲区/流的最佳方法是什么?
回答by josh3736
The request module buffers the response for you. In the callback, bodyisa string (or Buffer).
请求模块为您缓冲响应。在回调中,body是一个字符串(或Buffer)。
You only get a stream back from request if you don't provide a callback; request()returnsa Stream.
如果您不提供回调,您只会从请求中获得一个流;request()返回一个 Stream.
See the docs for more detail and examples.
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 nullencoding.
request 假定响应是文本,因此它尝试将响应正文转换为 sring(无论 MIME 类型如何)。这将损坏二进制数据。如果要获取原始字节,请指定一个nullencoding.
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.
});
});
回答by DenoFiend
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'
};
set encoding to null, return Buffer.
将编码设置为空,返回缓冲区。
回答by 7zark7
Have you tried piping this?:
你有没有试过管道这个?:
request.get('http://google.com/doodle.png').pipe(request.put('{your mongo path}'))
(Though not familiar enough with Mongo to know if it supports direct inserts of binary data like this, I know CouchDB and Riak do.)
(虽然对 Mongo 不够熟悉,不知道它是否支持像这样直接插入二进制数据,但我知道 CouchDB 和 Riak 支持。)
回答by Jaap Weijland
Nowadays, you can easily retreive a file in binary with Node 8, RequestJS and async await. I used the following:
如今,您可以使用 Node 8、RequestJS 和 async await 轻松检索二进制文件。我使用了以下内容:
const buffer = await request.get(pdf.url, { encoding: null });
The response was a Buffer containing the bytes of the pdf. Much cleaner than big option objects and old skool callbacks.
响应是一个包含 pdf 字节的缓冲区。比大选项对象和旧的 skool 回调更干净。

