tiny-eventsource

Tiny EventSource for API servers

Usage no npm install needed!

<script type="module">
  import tinyEventsource from 'https://cdn.skypack.dev/tiny-eventsource';
</script>

README

tiny-eventsource

build status

Tiny EventSource for API servers.

Attributes

heartbeat.event string

Default is message.

heartbeat.ms int

Default is 0. If greater than 0 a heart beat will be created from init().

heartbeat.msg string

Default is ping. Message sent if heartbeat.ms is greater than 0.

API

constructor([heartbeat], [...msgs])

Creates an EventSource instance with optional messages to be transmitted on successful connection.

init(req, res)

Initializes an Event Source stream.

send(msg[, event, id]);

Sends a message over an existing EventSource.

Example

const streams = new Map(),
    eventsource = require("tiny-eventsource"),
    {STATUS_CODES} = require("http");

module.exports = (req, res) => {
    if (req.isAuthenticated()) {
        const id = req.user.id;

        if (!streams.has(id)) {
            streams.set(id, eventsource({ms: 2e4}, "connected"));
        }

        streams.get(id).init(req, res);
    } else {
        res.statusCode = 401;
        res.writeHead(res.statusCode, {headers: {"cache-control": "no-cache, must re-validate"}})
        res.end(STATUS_CODES[res.statusCode]);
    }
};