Created
November 7, 2022 22:07
-
-
Save gtrabanco/d0d5b2e00ed1468d97093468bb7bc698 to your computer and use it in GitHub Desktop.
sse express sample
This file contains 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
import { randomUUID } from "crypto"; | |
import { EventEmitter } from "events"; | |
import express from "express"; | |
function formatEvent(event) { | |
const { event = "message", data = {}, id = randomUUID(), retry = undefined } = event; | |
const resultString = retry ? `retry: ${retry}\n` : ""; | |
resultString += `id: ${id}\n`; | |
resultString += `event: ${event}\n`; | |
resultString += `data: ${JSON.stringify(data)}\n\n`; | |
return resultString; | |
} | |
const sseEvents = new EventEmitter() | |
export const sse = (data) => { | |
sseEvents.emit("/events", `data: ${JSON.stringify(data)}\n\n`); | |
} | |
let counter = 0; | |
setInterval(() => { | |
sse({ payload: {date: Date.now(), times: counter++} }); | |
}, 2000) | |
export const app = express(); | |
let times = 0; | |
app.get("/events", (req, res) => { | |
res.set({ | |
"Content-Type": "text/event-stream", // application/x-dom-event-stream | |
"Cache-Control": "no-cache, no-transform", | |
Connection: "keep-alive", | |
"X-Accel-Buffering": "no", | |
}); | |
res.flushHeaders(); | |
res.write("retry: 10000\n\n"); | |
sseEvents.on(req.originalUrl.pathname, (data) => { | |
res.write(data); | |
}); | |
}); | |
app.listen(3000, () => { | |
console.log("Listening on port 3000"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment