You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

29 lines
672 B

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