Spaces:
Sleeping
Sleeping
File size: 937 Bytes
d605f27 |
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 |
import {EventEmitter} from "events";
export default class StreamParser extends EventEmitter {
reader: ReadableStreamReader<Uint8Array>;
separator: string;
constructor (reader, {separator = "\n\n\n\n"} = {}) {
super();
this.reader = reader;
this.separator = separator;
}
async read () {
let buffer = "";
while (true) {
const {done, value} = await this.reader.read();
if (value) {
const deltaText = new TextDecoder("utf-8").decode(value);
buffer += deltaText;
while (true) {
const separatorIndex = buffer.indexOf(this.separator);
if (separatorIndex >= 0) {
const part = buffer.substr(0, separatorIndex);
this.emit("data", part);
buffer = buffer.substr(separatorIndex + this.separator.length);
}
else
break;
}
}
if (done)
break;
}
if (buffer) {
//console.debug("last buffer:", buffer);
this.emit("data", buffer);
}
}
};
|