节点超级代理响应类型('blob')与缓冲区(真)

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

由于 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 已弃用(在客户端),应该使用

superAgentRequest.responseType('blob');

这似乎在 NodeJS 上运行良好,但我也发现了这个 github issue 他们使用

superAgentRequest.buffer(true);

同样有效。所以我想知道在 NodeJS 中请求二进制数据的首选方法是什么?

根据文档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.

因此要解析其他响应类型,您需要设置.buffer(true).parse(fn)。但是如果你不想解析响应那么就不需要设置 buffer(true).

根据 superagent 的 source-code, 使用 responseType() 方法在内部将 buffer 标志设置为 true,即与手动将其设置为 true.[=16 相同=]

在处理 binary-data/octet-streams 的情况下,一个 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));
  });
};

在这两种情况下都使用了这个解析器,这解释了行为。因此,您可以使用上述任何一种方法来处理二进制 data/octet-streams.