Skip to content

Instantly share code, notes, and snippets.

@bharathvaj-ganesan
Last active October 31, 2021 15:12
Show Gist options
  • Save bharathvaj-ganesan/a737211f203b42be63dd49f4a4047059 to your computer and use it in GitHub Desktop.
Save bharathvaj-ganesan/a737211f203b42be63dd49f4a4047059 to your computer and use it in GitHub Desktop.
// events.js
const EventEmitter = require('eventemitter3');
const emitter = new EventEmitter();
function subscribe(req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive'
});
// Heartbeat
const nln = function() {
res.write('\n');
};
const hbt = setInterval(nln, 15000);
const onEvent = function(data) {
res.write('retry: 500\n');
res.write(`event: event\n`);
res.write(`data: ${JSON.stringify(data)}\n\n`);
};
emitter.on('event', onEvent);
// Clear heartbeat and listener
req.on('close', function() {
clearInterval(hbt);
emitter.removeListener('event', onEvent);
});
}
function publish(eventData) {
// Emit events here recieved from Github/Twitter APIs
emitter.emit('event', eventData);
}
module.exports = {
subscribe, // Sending event data to the clients
publish // Emiting events from streaming servers
};
// App.js
const express = require('express');
const events = require('./events');
const port = process.env.PORT || 5001;
const app = express();
app.get('/events', cors(), events.subscribe);
app.listen(port, function() {
console.log('Listening on', port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment