-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathstram-cache.js
More file actions
33 lines (29 loc) · 823 Bytes
/
stram-cache.js
File metadata and controls
33 lines (29 loc) · 823 Bytes
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
import { Readable } from 'stream';
export class StreamCache {
constructor(inputStream, cacheThreshold = 4000) {
this.cacheStream = new Readable({
read() { }
});
this.cache = [];
this.cacheThreshold = cacheThreshold;
inputStream.on('data', this._addDataToCache);
inputStream.on('end', () => {
this._emitCache();
this.cacheStream.emit('end');
});
}
_addDataToCache = (data) => {
this.cache.push(data);
if (this.cache.length >= this.cacheThreshold) {
this._emitCache();
}
}
_emitCache() {
if (!this.cache.length) return
this.cacheStream.push(JSON.stringify(this.cache));
this.cache = [];
}
stream() {
return this.cacheStream;
}
}