-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreceive-stream-buffer.js
More file actions
67 lines (60 loc) · 1.86 KB
/
receive-stream-buffer.js
File metadata and controls
67 lines (60 loc) · 1.86 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
/* eslint-disable no-underscore-dangle */
const {Writable} = require('stream');
const {Buffer} = require('buffer');
class ReceiveStreamBuffer extends Writable {
constructor({
logger, bufferSizeIncrement = 10 * 1024 * 1024, verbose = false, ...options
}) {
super(options);
this.fd = null;
if (!logger) {
throw new Error('Missing logger parameter');
}
this.logger = logger;
this.verbose = verbose;
this.bufferSizeIncrement = bufferSizeIncrement;
this.init()
}
init() {
this.buffer = Buffer.allocUnsafe(2 * this.bufferSizeIncrement);
this.bufferLength = 2 * this.bufferSizeIncrement;
this.bufferUsed = 0;
}
_construct(callback) {
callback();
}
_write(chunk, encoding, callback) {
if (encoding !== 'buffer') {
callback(new Error(`Unexpected encoding ${encoding}`));
} else {
while (chunk.length + this.bufferUsed > this.bufferLength) {
const origBuffer = this.buffer;
const origBufferLength = this.buffer.length;
this.buffer = Buffer.allocUnsafe(this.bufferLength + this.bufferSizeIncrement);
this.bufferLength += this.bufferSizeIncrement;
if (this.verbose) {
this.logger.debug(`grow buffer: old size=${origBufferLength}, needed=${chunk.length + this.bufferUsed}, new size=${this.bufferLength}`);
}
origBuffer.copy(this.buffer, 0, 0, this.bufferUsed);
}
chunk.copy(this.buffer, this.bufferUsed);
this.bufferUsed += chunk.length;
callback();
}
}
_final(callback) {
if (this.verbose) {
this.logger.debug(`finished: Collected ${this.bufferUsed} bytes`);
}
callback(null);
}
getData() {
return this.buffer.subarray(0, this.bufferUsed);
}
resetData(callback) {
this.buffer.fill(0);
this.init();
callback();
}
}
module.exports = ReceiveStreamBuffer;