index.js 860 B

123456789101112131415161718192021222324252627282930313233343536
  1. 'use strict';
  2. const PassThrough = require('stream').PassThrough;
  3. const zlib = require('zlib');
  4. module.exports = res => {
  5. // TODO: use Array#includes when targeting Node.js 6
  6. if (['gzip', 'deflate'].indexOf(res.headers['content-encoding']) === -1) {
  7. return res;
  8. }
  9. const unzip = zlib.createUnzip();
  10. const stream = new PassThrough();
  11. stream.httpVersion = res.httpVersion;
  12. stream.headers = res.headers;
  13. stream.rawHeaders = res.rawHeaders;
  14. stream.trailers = res.trailers;
  15. stream.rawTrailers = res.rawTrailers;
  16. stream.setTimeout = res.setTimeout.bind(res);
  17. stream.statusCode = res.statusCode;
  18. stream.statusMessage = res.statusMessage;
  19. stream.socket = res.socket;
  20. unzip.on('error', err => {
  21. if (err.code === 'Z_BUF_ERROR') {
  22. stream.end();
  23. return;
  24. }
  25. stream.emit('error', err);
  26. });
  27. res.pipe(unzip).pipe(stream);
  28. return stream;
  29. };