https://github.com/isocroft/ssenode
A library for setting up server-sent events in Node.js
https://github.com/isocroft/ssenode
eventsource nodejs server-sent-events sse stream
Last synced: 2 months ago
JSON representation
A library for setting up server-sent events in Node.js
- Host: GitHub
- URL: https://github.com/isocroft/ssenode
- Owner: isocroft
- License: mit
- Created: 2019-10-18T17:05:35.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2020-12-28T10:43:20.000Z (over 5 years ago)
- Last Synced: 2025-08-09T15:49:31.356Z (11 months ago)
- Topics: eventsource, nodejs, server-sent-events, sse, stream
- Language: JavaScript
- Size: 51.8 KB
- Stars: 3
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
Awesome Lists containing this project
README
# server-events-nodejs
A library for setting up server-sent events in Node.js. This library was inspired by work done by [
Dino Paskvan](https://www.github.com/dpskvn) on [express-sse](https://www.github.com/dpskvn/express-sse)
## Install
>npm
`npm install server-events-nodejs --save`
>yarn
`yarn add server-events-nodejs`
## Usage
```js
const { Source, EventStream } = require('server-events-nodejs');
const express = require('express');
const cuid = require('cuid');
const port = "8080";
const source = new Source(cuid);
const app = express();
app.listen(port, () => {
console.log('Server ready!');
});
app.use(
EventStream.init(source, {
no_ids: false, // if you need id: key/value (from the cuid lib) as part of the text-stream response - set to 'true'
pad_for_ie: false, // if the HTTP request is from an IE 8/9 browser - set to 'true'
prefered_event_name: 'update', // if you need event: key/value (here set to 'update') as part of the text-stream resposne - set here to whatever you like
prefer_event_name: true // enforce the prefered event name to be used in the text-stream response
})
);
app.get('/notifications', function(req){
console.log('headers: ', req.headers);
// send comment: '!this is a comment!'
// send with event name: 'update'
// send with retry: 4500 (4.5 seconds)
source.send({
ids: [ '123', '456' ],
timestamp: Date.now()
},
'!this is a comment!', // comment
'update', // event
4500 // retry
);
});
```
>Then, you need to setup the front-end accordingly
```js
const evtSource = new EventSource('http://localhost:8080/notifications');
evtSource.addEventListener('open', function(e) {
console.log("connection is open!");
}, false);
evtSource.addEventListener('error', function(e) {
console.error(e);
evtSource.close();
})
evtSource.addEventListener('update', function(e) {
console.log("message: ", JSON.parse(e.data));
}, false);
/* - logs to console -
connection is open!
message: {
"ids": [
"123",
"456"
],
"timestamp": 1608970168797
}
*/
```
## License
MIT