• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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	stream.httpVersion = res.httpVersion;
15	stream.headers = res.headers;
16	stream.rawHeaders = res.rawHeaders;
17	stream.trailers = res.trailers;
18	stream.rawTrailers = res.rawTrailers;
19	stream.setTimeout = res.setTimeout.bind(res);
20	stream.statusCode = res.statusCode;
21	stream.statusMessage = res.statusMessage;
22	stream.socket = res.socket;
23
24	unzip.on('error', err => {
25		if (err.code === 'Z_BUF_ERROR') {
26			stream.end();
27			return;
28		}
29
30		stream.emit('error', err);
31	});
32
33	res.pipe(unzip).pipe(stream);
34
35	return stream;
36};
37