forked from sindresorhus/decompress-response
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
42 lines (32 loc) · 1.03 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
'use strict';
const {
pipeline: streamPipeline,
PassThrough: PassThroughStream
} = require('stream');
const zlib = require('zlib');
const mimicResponse = require('mimic-response');
const decompressResponse = response => {
const contentEncoding = (response.headers['content-encoding'] || '').toLowerCase();
if (!['gzip', 'deflate', 'br'].includes(contentEncoding)) {
return response;
}
// TODO: Remove this when targeting Node.js 12.
const isBrotli = contentEncoding === 'br';
if (isBrotli && typeof zlib.createBrotliDecompress !== 'function') {
return response;
}
const decompress = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip();
const stream = new PassThroughStream();
decompress.on('error', error => {
// Ignore empty response
if (error.code === 'Z_BUF_ERROR') {
stream.end();
return;
}
stream.emit('error', error);
});
const finalStream = streamPipeline(response, decompress, stream, () => {});
mimicResponse(response, finalStream);
return finalStream;
};
module.exports = decompressResponse;