source: node_modules/decompress-response/index.js@ 81bc7da

finki-main main
Last change on this file since 81bc7da was 81bc7da, checked in by Klimentina Efremova <klimentina08642@…>, 3 months ago

Initial commit

  • Property mode set to 100644
File size: 1.3 KB
Line 
1'use strict';
2const {Transform, PassThrough} = require('stream');
3const zlib = require('zlib');
4const mimicResponse = require('mimic-response');
5
6module.exports = response => {
7 const contentEncoding = (response.headers['content-encoding'] || '').toLowerCase();
8
9 if (!['gzip', 'deflate', 'br'].includes(contentEncoding)) {
10 return response;
11 }
12
13 // TODO: Remove this when targeting Node.js 12.
14 const isBrotli = contentEncoding === 'br';
15 if (isBrotli && typeof zlib.createBrotliDecompress !== 'function') {
16 response.destroy(new Error('Brotli is not supported on Node.js < 12'));
17 return response;
18 }
19
20 let isEmpty = true;
21
22 const checker = new Transform({
23 transform(data, _encoding, callback) {
24 isEmpty = false;
25
26 callback(null, data);
27 },
28
29 flush(callback) {
30 callback();
31 }
32 });
33
34 const finalStream = new PassThrough({
35 autoDestroy: false,
36 destroy(error, callback) {
37 response.destroy();
38
39 callback(error);
40 }
41 });
42
43 const decompressStream = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip();
44
45 decompressStream.once('error', error => {
46 if (isEmpty && !response.readable) {
47 finalStream.end();
48 return;
49 }
50
51 finalStream.destroy(error);
52 });
53
54 mimicResponse(response, finalStream);
55 response.pipe(checker).pipe(decompressStream).pipe(finalStream);
56
57 return finalStream;
58};
Note: See TracBrowser for help on using the repository browser.