-
Notifications
You must be signed in to change notification settings - Fork 0
/
streamer.js
68 lines (68 loc) · 1.46 KB
/
streamer.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
export default class Streamer {
// The stream delimiter
#delimiter;
#ignore;
// Class constructor
constructor(delimiter = /\n/g, ignore = /\r/g) {
this.#delimiter = delimiter;
this.#ignore = ignore;
}
// Line buffer
#buffer = '';
// Receiver
receive(buf) {
const
str = buf.toString().replace(this.#ignore, ''),
blocks = str.split(this.#delimiter);
blocks.forEach((blk, i) => {
if (i + 1 < blocks.length) {
// Immediately process this block
if (i === 0)
this.#processBlock(this.#buffer + blk);
else
this.#processBlock(blk);
} else {
// Push this block to buffer
// and wait for next delimiter
if (i == 0)
this.#buffer = this.#buffer + blk;
else
this.#buffer = blk;
}
})
}
// Wait queue
#queue = [];
// Line Processor
#processBlock(blk) {
this.#queue = this.#queue.filter(f => !f(blk));
}
// Event registerer
waitFor(cond) {
if (typeof cond === 'function')
return new Promise(res => {
this.#queue.push(blk => {
const match = cond(blk);
if (match) res(match);
return match;
})
})
if (typeof cond === 'string')
return new Promise(res => {
this.#queue.push(blk => {
const match = blk === cond;
if (match) res(blk);
return match;
})
})
if (cond instanceof RegExp)
return new Promise(res => {
this.#queue.push(blk => {
cond.lastIndex = 0;
const match = cond.exec(blk);
if (match) res(match);
return match;
})
})
}
}