UNPKG

672 BJavaScriptView Raw
1const express = require('express')
2const serveStatic = require('serve-static')
3const SseStream = require('ssestream')
4
5const app = express()
6app.use(serveStatic(__dirname))
7app.get('/sse', (req, res) => {
8 console.log('new connection')
9
10 const sseStream = new SseStream(req)
11 sseStream.pipe(res)
12 const pusher = setInterval(() => {
13 sseStream.write({
14 event: 'server-time',
15 data: new Date().toTimeString()
16 })
17 }, 1000)
18
19 res.on('close', () => {
20 console.log('lost connection')
21 clearInterval(pusher)
22 sseStream.unpipe(res)
23 })
24})
25
26app.listen(8080, (err) => {
27 if (err) throw err
28 console.log('server ready on http://localhost:8080')
29})