| Leo Repp | 58b9f11 | 2021-11-22 11:57:47 +0100 | [diff] [blame^] | 1 | 'use strict'; |
| 2 | const PassThrough = require('stream').PassThrough; |
| 3 | const zlib = require('zlib'); |
| 4 | const mimicResponse = require('mimic-response'); |
| 5 | |
| 6 | module.exports = response => { |
| 7 | // TODO: Use Array#includes when targeting Node.js 6 |
| 8 | if (['gzip', 'deflate'].indexOf(response.headers['content-encoding']) === -1) { |
| 9 | return response; |
| 10 | } |
| 11 | |
| 12 | const unzip = zlib.createUnzip(); |
| 13 | const stream = new PassThrough(); |
| 14 | |
| 15 | mimicResponse(response, stream); |
| 16 | |
| 17 | unzip.on('error', err => { |
| 18 | if (err.code === 'Z_BUF_ERROR') { |
| 19 | stream.end(); |
| 20 | return; |
| 21 | } |
| 22 | |
| 23 | stream.emit('error', err); |
| 24 | }); |
| 25 | |
| 26 | response.pipe(unzip).pipe(stream); |
| 27 | |
| 28 | return stream; |
| 29 | }; |