Search code examples
node.jssuperagent

node-superagent responseType('blob') vs. buffer(true)


Due to the deprecation of request, we're currently rewriting the request-service in our node app with superagent. So far all looks fine, however we're not quite sure how to request binary data/octet-stream and to process the actual response body as a Buffer. According to the docs (on the client side) one should use

superAgentRequest.responseType('blob');

which seems to work fine on NodeJS, but I've also found this github issue where they use

superAgentRequest.buffer(true);

which works just as well. So I'm wondering what the preferred method to request binary data in NodeJS is?


Solution

  • According to superagent's source-code, using the responseType() method internally sets the buffer flag to true, i.e. the same as setting it manually to true.

    In case of dealing with binary-data/octet-streams, a binary data parser is used, which is in fact just a simple buffer:

    module.exports = (res, fn) => {
      const data = []; // Binary data needs binary storage
    
      res.on('data', chunk => {
        data.push(chunk);
      });
      res.on('end', () => {
        fn(null, Buffer.concat(data));
      });
    };
    

    In both cases this parser is used, which explains the behaviour. So you can go with either of the mentioned methods to deal with binary data/octet-streams.