Last active
June 15, 2023 00:42
-
-
Save ggorlen/0912f9cb70bb733f6e11cf82efb92b6b to your computer and use it in GitHub Desktop.
Server-sent events example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // see: https://stackoverflow.com/a/67184841/6243352 | |
| const express = require("express"); | |
| const app = express(); | |
| app.get("/stream", (req, res) => { | |
| res.writeHead(200, { | |
| //"Access-Control-Allow-Origin": "*", | |
| //"Content-Encoding": "none", | |
| "Connection": "keep-alive", | |
| "Cache-Control": "no-cache", | |
| "Content-Type": "text/event-stream", | |
| }); | |
| let counter = 0; | |
| const interval = setInterval(() => { | |
| const chunk = JSON.stringify({chunk: counter++}); | |
| res.write(`data: ${chunk}\n\n`); | |
| }, 100); | |
| res.on("close", () => { | |
| clearInterval(interval); | |
| res.end(); | |
| }); | |
| }); | |
| app.get("/", (request, response) => { | |
| const html = | |
| `<!DOCTYPE html> | |
| <html lang="en"> | |
| <head><title>SSE POC</title></head> | |
| <body> | |
| <script> | |
| (async () => { | |
| const response = await fetch("/stream"); | |
| if (!response.ok) { | |
| throw Error(response.statusText()); | |
| } | |
| for (const reader = response.body.getReader(); ; ) { | |
| const {value, done} = await reader.read(); | |
| if (done) { | |
| break; | |
| } | |
| const chunk = new TextDecoder().decode(value); | |
| const subChunks = chunk.split(/(?<=})\\n\\ndata: (?={)/); | |
| for (const subChunk of subChunks) { | |
| const payload = subChunk.replace(/^data: /, ""); | |
| document.body.innerText = JSON.parse(payload).chunk; | |
| } | |
| } | |
| })(); | |
| </script> | |
| </body> | |
| </html>`; | |
| response.send(html); | |
| }); | |
| const listener = app.listen(process.env.PORT || 3000, () => | |
| console.log(`Your app is listening on port ${listener.address().port}`) | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment