Getting binary content in node.js with http.request

后端 未结 7 1476
广开言路
广开言路 2020-12-02 16:50

I would like to retrieve binary data from an https request.

I found a similar question that uses the request method, Getting binary content in Node

7条回答
  •  心在旅途
    2020-12-02 17:28

    The accepted answer did not work for me (i.e., setting encoding to binary), even the user who asked the question mentioned it did not work.

    Here's what worked for me, taken from: http://chad.pantherdev.com/node-js-binary-http-streams/

    http.get(url.parse('http://myserver.com:9999/package'), function(res) {
        var data = [];
    
        res.on('data', function(chunk) {
            data.push(chunk);
        }).on('end', function() {
            //at this point data is an array of Buffers
            //so Buffer.concat() can make us a new Buffer
            //of all of them together
            var buffer = Buffer.concat(data);
            console.log(buffer.toString('base64'));
        });
    });
    

    Edit: Update answer following a suggestion by Semicolon

提交回复
热议问题