Get the whole response body when the response is chunked?

前端 未结 7 987
旧巷少年郎
旧巷少年郎 2020-12-08 06:32

I\'m making a HTTP request and listen for \"data\":

response.on(\"data\", function (data) { ... })

The problem is that the response is chun

7条回答
  •  一整个雨季
    2020-12-08 07:09

    In order to support the full spectrum of possible HTTP applications, Node.js's HTTP API is very low-level. So data is received chunk by chunk not as whole.
    There are two approaches you can take to this problem:

    1) Collect data across multiple "data" events and append the results
    together prior to printing the output. Use the "end" event to determine
    when the stream is finished and you can write the output.

    var http = require('http') ;
    http.get('some/url' , function (resp) {
        var respContent = '' ;
        resp.on('data' , function (data) {
            respContent += data.toString() ;//data is a buffer instance
        }) ;
        resp.on('end' ,  function() {
            console.log(respContent) ;
        }) ;
    }).on('error' , console.error) ;
    

    2) Use a third-party package to abstract the difficulties involved in
    collecting an entire stream of data. Two different packages provide a
    useful API for solving this problem (there are likely more!): bl (Buffer
    List) and concat-stream; take your pick!

    var http = require('http') ;
    var bl = require('bl') ;
    
    http.get('some/url', function (response) {
        response.pipe(bl(function (err, data) {
            if (err) {
                return console.error(err)
            }
            data = data.toString() ;
            console.log(data) ;
        })) 
    }).on('error' , console.error) ;
    

提交回复
热议问题