UNPKG

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