-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
74 lines (53 loc) · 1.88 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
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
72
73
74
const stream = require('stream');
const async = require('async');
class StreamBuffer extends stream.Writable {
constructor(options) {
super(options);
options = options || {};
this.maxBufferSize = options.maxBufferSize || StreamBuffer.MAX_BUFFER_SIZE;
this.buffered = [];
this.bufferedAmount = 0;
this.hadError = null;
this.didFinish = false;
this.once('finish', () => this.didFinish = true);
this.once('error', (error) => this.hadError = error);
}
_write(chunk, encoding, callback) {
if (this.bufferedAmount === this.maxBufferSize)
return setImmediate(callback);
if (this.bufferedAmount + chunk.length > this.maxBufferSize) {
chunk = chunk.slice(0, this.maxBufferSize - this.bufferedAmount);
}
this.bufferedAmount += chunk.length;
this.buffered.push(chunk);
setImmediate(callback);
}
toString(encoding, callback) {
if (typeof encoding === 'function') {
callback = encoding;
encoding = 'utf8';
}
encoding = encoding || 'utf8';
if (!callback) {
return this.toBuffer().toString(encoding);
}
this.toBuffer((error, buffer) => {
if (error) return callback(error);
callback(null, buffer.toString(encoding));
});
}
toBuffer(callback) {
if (!callback) {
return Buffer.concat(this.buffered);
}
if (this.hadError || this.didFinish) {
return setImmediate(callback, this.hadError, this.toBuffer());
}
async.race([
(callback) => this.on('error', callback),
(callback) => this.on('finish', () => callback(null, this.toBuffer()))
], callback);
}
}
StreamBuffer.MAX_BUFFER_SIZE = 10 * 1024 * 1024;
module.exports = StreamBuffer;