npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

event-flare

v1.0.2

Published

Stream events from server to client seemlessly and reliably with Server sent events

Downloads

212

Readme

Event Flare

Static Badge Static Badge

Effortlessly stream real-time events from your server to clients using Server-Sent Events (SSE). This package provides an easy-to-use API for implementing SSE, allowing you to establish a one-to-one/ one-to-many connection where the server can continuously send event updates to clients with minimal setup.

Features

  • Unicast event to a single client.
  • Broadcast event to multiple clients at once.
  • Compatible with all popular Node.js HTTP frameworks like Express, http, Koa.
  • Ships with Typescript types.
  • Event history with configurable size.
  • Comes with retry mechanism with configurable reconnection timeout.
  • events are sent with last event id for more robustness.
  • Heartbeat mechanism for keeping connection alive with configurable heartbeatInterval.
  • Supports event-source-polyfill

Installation

    npm install event-flare

Usage

Stream events to single client:

Express Server

import { Session } from "event-flare"
import express from "express"

const app = express()
app.get('/', (req, res) => {
    const session = new Session(req, res)
    const dataToSend = {
        stockName: "AAPL",
        currentStockPrice: "245.65"
    }
    session.sendMessage(JSON.stringify(dataToSend))
}).listen(PORT)

Node.js http module

import { Session } from "event-flare"
import http from "http"

http.createServer((req, res) => {
    const session = new Session(req, res)
    const dataToSend = {
        stockName: "AAPL",
        currentStockPrice: "245.65"
    }
    session.sendMessage(JSON.stringify(dataToSend))
}).listen(PORT)

Koa

import { Session } from "event-flare"
import { PassThrough } from "stream"
import Koa from "koa"

const app = new Koa()
app.use(async ctx => {
    const req = ctx.req
    const res = ctx.res
    ctx.respond = false
    const stream = new PassThrough();
    ctx.body = stream
    const session = new Session(req, res)
    const dataToSend = {
        stockName: "AAPL",
        currentStockPrice: "245.65"
    }
    session.sendMessage(JSON.stringify(dataToSend))
}).listen(PORT)

Bind events to a particular eventName:

When sending data over sse, we can use eventName to describe an event type. To do this with event-flare, pass the eventName in the sendMessage method.

const session = new Session(req, res)
const msg = "mock data"
const eventType = "AAPL-stock-price"
session.sendMessage(msg, eventType)

This will send the following SPEC compliant SSE event:

    event: AAPL-stock-price
    data: mock data
    ...

Configure session parameters:

You can configure/ pass the following to the session Object:

  • heartbeatInterval: send an empty heartbeat event after the specified time to keep connection open. Default is 45000 millis

  • retryInterval: time to wait before the client attemps to reconnect. Default is 1000 millis

  • historySize: Max event history size. Oldest events will be popped when this limit is reached. Default is 100

  • sessionId: You can pass a custom sessionId for a sesison.

const options = {
    heartbeatInterval: 20000,
    retryInterval: 2000,
    historySize: 500,
    sessionId: 'my-custom-session-id'
}
const session = new Session(req, res, options)

Get connection state for a particular session:

A session can either be in CONNECTED state or in DISCONNECTED state. To get the connection state, use the getConnectionState method.

const session = new Session(req, res)
const state = session.getConnectionState()

Broadcast events to multiple client:

To broadcast events to multiple clients, we first need to create a broadcast channel. This can be done by:

const broadcastStream = new BroadcastStream("some-channel-id")

After setting up the broadcast channel, we need to link client sessions with the broadcast channel. This can be done with the register() method:

broadcastStream.register(session)

Broadcasting can be done in 2 ways:

  1. Broadcast events to all the sessions associated with that channel. This can be done by using broadcastAll() method.
  2. Broadcast events to some sessions in that channel. This can be done by using broadcastSome() method.

The following code examples demonstrate both usages.

import { BroadcastStream } from "event-flare"

const channelId = "AAPL-subscribers"
const broadcastStream = new BroadcastStream(channelId)
const session = new Session(req, res)

//Session registration
broadcastStream.register(session)
const dataToSend = {
    stockName: "AAPL",
    currentStockPrice: "245.65"
}

//send message to all subscribers in that channel
broadcastStream.broadcastAll(JSON.stringify(dataToSend))

...

import { BroadcastStream } from "event-flare"

const channelId = "AAPL-subscribers"
const broadcastStream = new BroadcastStream(channelId)

const session1 = new Session(req, res)
const session2 = new Session(req, res)
const session3 = new Session(req, res)

broadcastStream.register(session1)
broadcastStream.register(session2)
broadcastStream.register(session3)

const dataToSend = {
    stockName: "AAPL",
    currentStockPrice: "245.65"
}

//send message to some subscribers in that channel
broadcastStream.broadcastSome(JSON.stringify(dataToSend), [session1, session2])

...

Evict a client from a broadcast channel:

To deregister a session from a broadcast channel, we can use the deregister() method. The deregister method expects to pass sessionId associated with the session to evict. SessionId can be fetched by calling getSessionId() method on a session object.

const sessionIdToEvict = session.getSessionId()
broadcastStream.deregister(sessionIdToEvict)

Get total active connections in a broadcast channel:

const totalConnections = broadcastStream.getActiveConnections()

Event Emitter:

Both Session and BroadcastStream extends EventEmitter and emit the following events:

  • message-sent: event is emitted at the end of sendMessage() method, after an event is sent to client.

  • session-closed: event is emitted when a client session is disconnected. Note that if a client session is bound to a broadcast channel, closing the session also evists it from the broadcast channel.

  • session-registered: event is emitted when a client session is registered to a BroadcastStream object.

  • session-deregistered: event is emitted when a client session is deregistered from a BroadcastStream object.

  • broadcast-success: event is emitted after the message is sent to some/ all sessions registered in the broadcast channel.

License

This project is licensed under the MIT License