Getting binary content in node.js with http.request

后端 未结 7 1461
广开言路
广开言路 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:30
    1. Don't call setEncoding() method, because by default, no encoding is assigned and stream data will be returned as Buffer objects
    2. Call Buffer.from() in on.data callback method to convert the chunk value to a Buffer object.
    http.get('my_url', (response) => {
      const chunks = [];
      response.on('data', chunk => chunks.push(Buffer.from(chunk))) // Converte `chunk` to a `Buffer` object.
        .on('end', () => {
          const buffer = Buffer.concat(chunks);
          console.log(buffer.toString('base64'));
        });
    });
    
    0 讨论(0)
提交回复
热议问题