-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathreadableClass.js
37 lines (28 loc) · 972 Bytes
/
readableClass.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
const {Readable} = require('stream');
const advices = [
"No ice for drinks? Use frozen vegetables.",
"If you feel alone, watcha horror movie before going to be. You won't feel alone anymore.",
"Don't have sex after chopping jalapeños",
"If you can't blind them with brilliance, baffle them with nonsense",
"Always borrow money from a pessimist, they won't expect it back"
];
class StreamFromArray extends Readable {
constructor(array){
super({ objectMode: true}); //encoding: 'UTF-8' => Converts buffer to string
this.array = array;
this.index = 0
}
_read() {
if(this.index <= this.array.length){
const chunk = {
data: this.array[this.index],
index: this.index
}
this.push(chunk);
this.index += 1;
}else this.push(null);
}
}
const adviceStream = new StreamFromArray(advices);
adviceStream.on('data', (chunk) => console.log(chunk));
adviceStream.on('end', () => console.log("done!"));