Skip to content

Instantly share code, notes, and snippets.

@lwe
Last active September 11, 2022 12:51
Show Gist options
  • Save lwe/8982052 to your computer and use it in GitHub Desktop.
Save lwe/8982052 to your computer and use it in GitHub Desktop.
Server-sent-events with trial for hapi and one with a plain node.js http server.
var Hapi = require('hapi');
var stream = require('stream');
// Create a server
var server = Hapi.createServer('localhost', 8000);
// Add a route
server.route({
method: 'GET',
path: '/hello',
handler: function(request, reply) {
reply("<script>" +
"var source = new EventSource('/events');" +
"source.onmessage = function(e) { console.log(e.data) };" +
"source.onerror = function(e) { console.error(e); };" +
"source.onopen = function(e) { console.info(e); };" +
"</script> " +
"Hello World, Open the debug console to see more...!");
}
});
// SSE
server.route({
method: 'GET',
path: '/events',
handler: function(request, reply) {
var channel = new stream.PassThrough
var interval = setInterval(function() {
channel.write("data: abcdef\n\n")
console.log("write data...");
}, 1000);
request.raw.req.on("close", function() {
console.error("oops listener closed");
clearInterval(interval);
});
reply(channel).code(200).type('text/event-stream').header('Connection', 'keep-alive').header('Cache-Control', 'no-cache');
}
});
// Start the server
server.start();
{
"name": "sse-example-failure",
"version": "0.0.0",
"description": "",
"main": "hapi.js",
"scripts": {
"start": "node hapi.js"
},
"dependencies": {
"hapi": "~2.3.0"
}
}
var http = require('http');
var stream = require('stream');
var server = http.createServer(function(request, response) {
// Handle SSE requests
if (request.url == "/events") {
var channel = new stream.PassThrough
var interval = setInterval(function() {
channel.write("data: abcdef\n\n");
console.log("write data...");
}, 1000);
response.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'connection': 'keep-alive', 'cache-control': 'no-cache' });
response.on("close", function() { clearInterval(interval); });
channel.pipe(response);
}
// Provide the "UI"
else {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end("<script>" +
"var source = new EventSource('/events');" +
"source.onmessage = function(e) { console.log(e.data) };" +
"source.onerror = function(e) { console.error(e); };" +
"source.onopen = function(e) { console.info(e); };" +
"</script> " +
"Hello World, Open the debug console to see more...!");
}
});
// Start server
server.listen(8000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment