Last active
September 30, 2015 23:58
-
-
Save clee/1883462 to your computer and use it in GitHub Desktop.
EventSource demo code
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
$.ready(function() { | |
var source = new EventSource("/events"); | |
source.addEventListener('data', function(e) { | |
$("#content").append(e.data + "\n"); | |
}, false); | |
}); |
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
var express = require('express'); | |
var fs = require('fs'); | |
// change this to some other log file that doesn't require root permissions to read :) | |
var logfile = '/var/log/messages'; | |
var app = module.exports = express(); | |
app.use(express.bodyParser()); | |
app.use(express.methodOverride()); | |
app.use(express.static(__dirname + '/public')); | |
app.use(function(err, req, res, next) { | |
console.log('error: ' + err ); | |
}); | |
app.configure('development', function(){ | |
app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); | |
}); | |
app.configure('production', function(){ | |
app.use(express.errorHandler()); | |
}); | |
app.get('/', function(req, res) { res.redirect('/index.html') }); | |
app.get('/events', function(req, res) { | |
res.writeHead(200, { | |
'Content-Type': 'text/event-stream', | |
'Connection': 'keep-alive', | |
'Cache-Control': 'no-cache', | |
}); | |
fs.open(logfile, 'r', function(err, fd) { | |
// Whenever new data is available to read, send it to the client | |
fs.watchFile(logfile, function(curr, prev) { | |
if (curr.size > prev.size) { | |
console.log("size: %d -> %d", prev.size, curr.size); | |
var size = curr.size - prev.size; | |
var data = new Buffer(size); | |
fs.read(fd, data, 0, size, prev.size, function(err, bytesRead, buffer) { | |
console.log("sending data over eventsource..."); | |
res.write("data: " | |
+ JSON.stringify({Body: buffer.toString('utf8')}) | |
+ "\n\n" | |
); | |
}); | |
} | |
}); | |
// If the client disconnects, let's not leak any resources | |
res.on('close', function() { | |
fs.unwatchFile(logfile); | |
fs.close(fd); | |
}); | |
}); | |
}); | |
var http = require('http'); | |
var server = http.createServer(app); | |
server.listen(process.env.PORT || 3000); | |
console.log("tailpipe listening on port %d in %s mode", server.address().port, app.settings.env); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment