-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path1-readable.js
51 lines (39 loc) · 955 Bytes
/
1-readable.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
'use strict';
const fs = require('node:fs');
// Contracts:
// - Readable
// - EventEmitter
// - AsyncIterator
const readable = fs.createReadStream('1-readable.js');
// Styles generating data:
// - fs.createReadStream or other API
// - readable.push()
// - Readable.from(async function *)
// - Readable.from(string or Buffer)
readable.on('error', (error) => {
console.log({ error });
});
readable.on('end', () => {
console.log({ event: 'end' });
});
readable.on('close', () => {
console.log({ event: 'close' });
});
// Styles of reading data from streams:
// - on('data')
// - on('readable')
// - .pipe()
// - AsyncIterable
// Style: on('data')
readable.on('data', (chunk) => {
console.log({ data: chunk });
});
// Style: on('readable')
readable.on('readable', () => {
let data = readable.read();
console.log({ event: 'readable' });
while (data !== null) {
console.log({ readable: data });
data = readable.read();
}
});