【问题标题】:How to buffer an HTTP response using the request module?如何使用请求模块缓冲 HTTP 响应?
【发布时间】:2012-12-18 04:57:06
【问题描述】:

我想将 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 的最佳方式是什么?

【问题讨论】:

    标签: node.js stream request


    【解决方案1】:

    现在,您可以使用 Node 8、RequestJS 和异步等待轻松检索二进制文件。我使用了以下内容:

    const buffer = await request.get(pdf.url, { encoding: null }); 
    

    响应是一个包含 pdf 字节的缓冲区。比大选项对象和旧的 skool 回调要干净得多。

    【讨论】:

      【解决方案2】:
      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。

      【讨论】:

        【解决方案3】:

        请求模块为您缓冲响应。在回调中,body 一个字符串(或Buffer)。

        如果你不提供回调,你只会从请求中得到一个流; request() 返回 Stream

        See the docs for more detail and examples.


        request 假定响应是文本,因此它会尝试将响应正文转换为 sring(无论 MIME 类型如何)。这将损坏二进制数据。如果要获取原始字节,请指定 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.
        
            }); 
        });
        

        【讨论】:

        • 感谢您的校准。我已经更新了我的问题。请看看您是否可以扩展您的答案。
        • 哇。谢谢你,它奏效了。这让我发疯了这么久。
        • thx 这行得通,但我看到当传递“编码:null”时,在回调中,正文是缓冲区而不是字符串。对我来说,这是它起作用的主要原因。
        【解决方案4】:

        你试过管道这个吗?:

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

        (虽然对 Mongo 不够熟悉,不知道它是否支持像这样直接插入二进制数据,但我知道 CouchDB 和 Riak 支持。)

        【讨论】:

        • 谢谢,但我不想使用管道。可以直接流式传输到 mongodb,但这意味着我将不得不使用我想避免的 Gridfs。
        • 这是 HTTP Rest,但您也可以通过管道传输到本地文件:github.com/mikeal/request#streaming
        猜你喜欢
        • 2018-01-05
        • 1970-01-01
        • 2020-12-03
        • 1970-01-01
        • 2020-04-24
        • 1970-01-01
        • 2014-03-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多