-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.html
52 lines (43 loc) · 1.15 KB
/
index.html
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
<html>
<head>
</head>
<body>
<h1>SSE: <span id="state"></span></h1>
<h3>Data: <span id="data"></span></h3>
<script type="module">
console.log("fetching...");
let res = await fetch('/countdown', {method: 'POST', headers: {'Accept': 'text/event-stream',}});
// read body as stream
console.log("reading...");
let reader = res.body.getReader();
// read stream
console.log("reading stream...");
while (true) {
let {done, value} = await reader.read();
if (done) {
console.log("done");
break;
}
apply(value);
}
function apply(input) {
const decoder = new TextDecoder("utf-8");
const raw = decoder.decode(input);
let ev, data;
raw.split("\n").forEach(line => {
const [key, value] = line.split(":");
if (key === "event") {
ev = value;
console.log("event", value);
} else if (key === "data") {
data = value;
console.log("data", value);
}
});
if (ev.trim() === "countdown" && data) {
document.getElementById("data").innerHTML = data;
}
}
</script>
</body>
</html>