Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Exemplo de SSE com Node.js
var source = new EventSource('http://localhost:8080');
source.addEventListener('message', function(data){
source.addEventListener('open', function(){
console.log('Conexão aberta!');
source.addEventListener('error', function(err){
require('http').Server(function(req, res){
// Setamos as headers para indicar um SSE e evitar cache
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Access-Control-Allow-Origin': '*',
'Connection': 'keep-alive'
// Iniciamos o envio da hora atual a cada segundo
var timer = setInterval(function(){
res.write('data:' + JSON.stringify({
date: new Date()
}) + '\n\n'); // Não esquecer o EOL duplo
}, 1000);
// Caso a conexão caia/pare/feche, precisamos parar o timer
req.on('close', function(){
}).listen(8080, '');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.