forked from forwardemail/superagent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunzip.js
More file actions
71 lines (59 loc) · 1.52 KB
/
unzip.js
File metadata and controls
71 lines (59 loc) · 1.52 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Module dependencies.
*/
const { StringDecoder } = require('string_decoder');
const Stream = require('stream');
const zlib = require('zlib');
/**
* Buffers response data events and re-emits when they're unzipped.
*
* @param {Request} req
* @param {Response} res
* @api private
*/
exports.unzip = (request, res) => {
const unzip = zlib.createUnzip();
const stream = new Stream();
let decoder;
// make node responseOnEnd() happy
stream.req = request;
unzip.on('error', (error) => {
if (error && error.code === 'Z_BUF_ERROR') {
// unexpected end of file is ignored by browsers and curl
stream.emit('end');
return;
}
stream.emit('error', error);
});
// pipe to unzip
res.pipe(unzip);
// override `setEncoding` to capture encoding
res.setEncoding = (type) => {
decoder = new StringDecoder(type);
};
// decode upon decompressing with captured encoding
unzip.on('data', (buf) => {
if (decoder) {
const string_ = decoder.write(buf);
if (string_.length > 0) stream.emit('data', string_);
} else {
stream.emit('data', buf);
}
});
unzip.on('end', () => {
stream.emit('end');
});
// override `on` to capture data listeners
const _on = res.on;
res.on = function (type, fn) {
if (type === 'data' || type === 'end') {
stream.on(type, fn.bind(res));
} else if (type === 'error') {
stream.on(type, fn.bind(res));
_on.call(res, type, fn);
} else {
_on.call(res, type, fn);
}
return this;
};
};