index.js 1023 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. 'use strict';
  2. const {PassThrough: PassThroughStream} = require('stream');
  3. const zlib = require('zlib');
  4. const mimicResponse = require('mimic-response');
  5. const decompressResponse = response => {
  6. const contentEncoding = (response.headers['content-encoding'] || '').toLowerCase();
  7. if (!['gzip', 'deflate', 'br'].includes(contentEncoding)) {
  8. return response;
  9. }
  10. const isBrotli = contentEncoding === 'br';
  11. if (isBrotli && typeof zlib.createBrotliDecompress !== 'function') {
  12. return response;
  13. }
  14. const decompress = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip();
  15. const stream = new PassThroughStream();
  16. mimicResponse(response, stream);
  17. decompress.on('error', error => {
  18. // Ignore empty response
  19. if (error.code === 'Z_BUF_ERROR') {
  20. stream.end();
  21. return;
  22. }
  23. stream.emit('error', error);
  24. });
  25. response.pipe(decompress).pipe(stream);
  26. return stream;
  27. };
  28. module.exports = decompressResponse;
  29. // TODO: remove this in the next major version
  30. module.exports.default = decompressResponse;