-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy path5-through.js
More file actions
53 lines (46 loc) · 1.14 KB
/
5-through.js
File metadata and controls
53 lines (46 loc) · 1.14 KB
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
'use strict';
const createTransform = () =>
new TransformStream({
start() {
// initialization
},
async transform(chunk, controller) {
const data = await chunk;
if (data === null) {
controller.terminate();
} else {
controller.enqueue(data.length);
}
},
flush() {
// finalization
},
});
const createWritable = () => {
const chunks = [];
const writableStream = new WritableStream({
write(chunk) {
console.log(`Value: ${chunk}`);
chunks.push(chunk);
},
close() {
console.log('Stream closed');
},
abort(err) {
console.log('Stream aborted');
console.error(err);
},
});
return { writableStream, chunks };
};
const main = async () => {
const url = 'https://developer.mozilla.org/';
const { body } = await fetch(url);
const transformStream = createTransform();
console.log({ transformStream });
const { writableStream, chunks } = createWritable();
await body.pipeThrough(transformStream).pipeTo(writableStream);
const total = chunks.reduce((a, b) => a + b);
console.log(`Bytes received: ${total}`);
};
main();