Created
February 21, 2023 02:37
-
-
Save todbot/4fbb2a3e2c273de0005b28a953e0de71 to your computer and use it in GitHub Desktop.
Simple SSE (Server Sent Events) server in NodeJs
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
// 20 Feb 2023 - @todbot / Tod Kurt, for carlynorama | |
// | |
// orig from: https://web.dev/eventsource-basics/ | |
var http = require('http'); | |
var fs = require('fs'); | |
var http_port = 8000 | |
console.log("starting server on port"+http_port) | |
http.createServer(function(req, res) { | |
if (req.headers.accept | |
// && req.headers.accept == 'text/event-stream' | |
) { | |
if (req.url == '/events') { | |
sendSSE(req, res); | |
} else { | |
res.writeHead(404); | |
res.end(); | |
} | |
} | |
}).listen(http_port); | |
function sendSSE(req, res) { | |
res.writeHead(200, { | |
'Content-Type': 'text/event-stream', | |
'Cache-Control': 'no-cache', | |
'Connection': 'keep-alive' | |
}); | |
// Sends a SSE every 2 seconds on a single connection. | |
setInterval(function() { | |
var id = (new Date()).toLocaleTimeString(); | |
var event_type = 'update' | |
var data_str = '{"time":"'+ (new Date()).toLocaleTimeString() + '"}' | |
constructSSE(res, id, event_type, data_str ) | |
}, 2000); | |
} | |
function constructSSE(res, id, event_type, data) { | |
//res.write('id: ' + id + '\n'); | |
res.write('event: ' + event_type + '\n'); | |
res.write("data: " + data + '\n\n'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment