Server-Sent Events Stream can send Server-Sent Events using Node.js.
$ npm install sse_stream
Server side
var http = require("http");
var SSEStream = require("sse_stream");
var fs = require("fs");
http.createServer(function(req, res){
if (req.headers["accept"] === "text/event-stream") {
var sse_stream = new SSEStream();
var exec = require('child_process').exec;
var child = exec("tail -f test.log");
res.writeHead(200, {
'Content-type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
child.stdout.pipe(sse_stream).pipe(res);
sse_stream.on("end", function() {
res.end();
});
readStream.on("end", function() {
res.removeAllListeners();
});
sse_stream.on("error", function(error) {
console.error("error " + error);
});
readStream.on("error", function(error) {
console.error("error " + error);
});
} else {
fs.createReadStream("index.html").pipe(res);
}
}).listen(8080);
Client side
index.html
<!DOCTYPE html>
<html>
<head>
<title>Server Sent Events</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
$(function() {
var source = new EventSource("/");
source.onmessage = function(event) {
$("p").append(event.data);
$('html, body').animate({
scrollTop: $(document).height()
}, 100);
};
});
</script>
</head>
<body>
<p></p>
</body>
</html>
install global
$ npm install sse_stream -g
$ sse_server --file test.log
$ sse_server --cmd "tail -f test.log"
$ sse_server --cmd "tail -f test.log" --port 3002