Skip to content

Instantly share code, notes, and snippets.

@jahfer
Last active December 23, 2015 11:49
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 jahfer/6631329 to your computer and use it in GitHub Desktop.
Save jahfer/6631329 to your computer and use it in GitHub Desktop.
Simple SSE Server in Node (taken from somewhere online!)
var PORT = 8081;
var http = require("http");
var fs = require("fs");
var url = require("url");
http.createServer(function (request, response) {
var parsedURL = url.parse(request.url, true);
var pathname = parsedURL.pathname;
if (pathname === "/admin/push") {
response.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Access-Control-Allow-Origin": "*"
});
response.write(":" + Array(2049).join(" ") + "\n"); // 2kB padding for IE
response.write("retry: 2000\n");
var lastEventId = Number(request.headers["last-event-id"]) || Number(parsedURL.query.lastEventId) || 0;
var timeoutId = 0;
var i = lastEventId;
var c = i + 100;
var f = function () {
if (++i < c) {
response.write("id: " + i + "\n");
var data = {
Topic: 'checkout',
EventName: 'view_cart',
Payload: {
cart_token: "65a190e348777cfb326d59eeaf44a56d"
}
};
response.write("data: " + JSON.stringify(data) + "\n\n");
timeoutId = setTimeout(f, 1000);
} else {
response.end();
}
};
f();
response.on("close", function () {
clearTimeout(timeoutId);
});
} else {
if (pathname === "/") {
pathname = "/index.html";
}
if (pathname === "/index.html" || pathname === "../eventsource.js") {
response.writeHead(200, {
"Content-Type": pathname === "/index.html" ? "text/html" : "text/javascript"
});
response.write(fs.readFileSync(__dirname + pathname));
}
response.end();
}
}).listen(PORT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment