Skip to content

Instantly share code, notes, and snippets.

@rniii
Created August 29, 2024 16:21
Show Gist options
  • Save rniii/f29b822e8ef6d8017cbc870411d441e4 to your computer and use it in GitHub Desktop.
Save rniii/f29b822e8ef6d8017cbc870411d441e4 to your computer and use it in GitHub Desktop.
import express from "express"
import { EventEmitter } from "node:events"
const app = express()
const chat = new EventEmitter()
app.use(express.urlencoded({ extended: true }))
app.get("/", (req, res) => res.send(`<!doctype html>
<html lang="en">
<h1>hello, chat!</h1>
<iframe src="/chat/history" frameborder="0"></iframe> <hr>
<iframe src="/chat" frameborder="0"></iframe>
</html>`))
app.get("/chat", (req, res) => res.send(`<form method="post" action="/chat/history">
<input id="text" name="text" placeholder="Send a message...">
</form>`))
app.get("/chat/history", (req, res) => {
res.set("Content-Type", "text/html")
res.write("<!doctype html>")
res.write("<meta charset=utf-8>")
res.write("<body><ul>")
const listen = (text) => res.write("<li>" + text)
chat.on("message", listen)
res.on("close", () => chat.off("message", listen))
})
app.post("/chat/history", (req, res) => {
chat.emit("message", req.body.text)
res.redirect("/chat#text")
})
app.listen(3000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment