Skip to content

Instantly share code, notes, and snippets.

@todbot
Created February 21, 2023 02:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save todbot/4fbb2a3e2c273de0005b28a953e0de71 to your computer and use it in GitHub Desktop.
Save todbot/4fbb2a3e2c273de0005b28a953e0de71 to your computer and use it in GitHub Desktop.
Simple SSE (Server Sent Events) server in NodeJs
// 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