Skip to content

Instantly share code, notes, and snippets.

@lifez
Created September 20, 2019 07:54
Show Gist options
  • Save lifez/11721ceb27e2ce1cf126bcd261591667 to your computer and use it in GitHub Desktop.
Save lifez/11721ceb27e2ce1cf126bcd261591667 to your computer and use it in GitHub Desktop.
const EventEmitter = require("eventemitter3")
const emitter = new EventEmitter()
const express = require("express")
const cors = require("cors")
var app = express()
const subscribe = (req, res) => {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive"
})
const onMessage = data => {
res.write(`data: ${JSON.stringify(data)}\n\n`)
}
emitter.on("message", onMessage)
req.on("close", function() {
emitter.removeListener("message", onMessage)
})
}
const publish = (req, res) => {
emitter.emit("message", req.body)
res.json({ message: "success" })
}
app.use(cors())
app.use(express.json())
app.post("/", publish)
app.get("/", subscribe)
app.listen(3000, () => {})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment