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

Viewed 1986

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?

2 Answers

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.

As per documentation https://visionmedia.github.io/superagent/

SuperAgent will parse known response-body data for you, currently supporting application/x-www-form-urlencoded, application/json, and multipart/form-data. You can setup automatic parsing for other response-body data as well:

You can set a custom parser (that takes precedence over built-in parsers) with the .buffer(true).parse(fn) method. If response buffering is not enabled (.buffer(false)) then the response event will be emitted without waiting for the body parser to finish, so response.body won't be available.

So to parse other response types, you will need to set .buffer(true).parse(fn). But if you do not want to parse response then no need to set buffer(true).

Related