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

http-event-stream

v0.2.0

Published

Create plain HTTP event streams using Server Sent Events (SSE).

Downloads

79

Readme

http-event-stream Build Status NPM Version

Create plain HTTP event streams using Server Sent Events (SSE) in node.js. Stream push notifications to the client without WebSockets.

Framework-agnostic: Works with Express, Koa and probably many more. Check out Differences to WebSockets below.

📡  Realtime events over plain HTTP 💡  Serve as a REST endpoint route ☁️  Stateless by design 👌  Simple unopinionated API

Installation

npm install http-event-stream
# or
yarn add http-event-stream

Usage

Using Express.js

const express = require("express")
const { streamEvents } = require("http-event-stream")

const app = express()

// Example event stream: Stream the current time
app.get("/time-stream", (req, res) => {
  streamSampleEvents(req, res)
})

app.listen(3000)

Using Koa.js

const Koa = require("koa")
const Router = require("koa-router")
const { createEventStream } = require("http-event-stream")

const app = new Koa()
const router = new Router()

// Example event stream: Stream the current time
router.get("/time-stream", (context) => {
  streamSampleEvents(req, res)

  // Don't close the request/stream after handling the route!
  context.respond = false
})

app
  .use(router.routes())
  .use(router.allowedMethods())
  .listen(3000)

Sample stream implementation

function streamSampleEvents (req, res) {
  const fetchEventsSince = async (lastEventId) => {
    return [ /* all events since event with ID `lastEventId` woud go here */ ]
  }
  return streamEvents(req, res, {
    async fetch (lastEventId) {
      // This method is mandatory to replay missed events after a re-connect
      return fetchEventsSince(lastEventId)
    },
    stream (streamContext) {
      // Sample events: Send an event every second
      const interval = setInterval(() => {
        streamContext.sendEvent({
          event: "time",
          data: {
            now: new Date().toISOString()
          }
        })
      }, 1000)

      // Return stream-closing function
      const unsubscribe = () => clearInterval(interval)
      return unsubscribe
    }
  })
}

A server-sent event sent via streamContext.sendEvent() or returned from fetch() has to have the following shape:

interface ServerSentEvent {
  data: string | string[]
  event?: string,
  id?: string
  retry?: number
}

See Using server-sent events - Fields.

API

See dist/index.d.ts.

Differences to WebSockets

Brief summary:

  • Automatic reconnecting out of the box
  • Unidirectional data flow
  • HTTP/2 multiplexing out of the box
  • No Connection: Upgrade - no special reverse proxy config

What do we use websockets for? Usually for streaming events from the server to client in realtime.

Server Sent Events (SSE) only do this one job, but do it really well. It's a simple protocol, using a normal HTTP connection, only streaming data from the server to the client.

You can pass parameters and headers from the client to the server when opening the stream, but the actual stream is read-only for the client.

It might sound like a strong limitation first, but actually it's a pretty clean approach: It makes the stream stateless and allows cool things like combining multiple streams into one which you could not easily do with a duplex stream.

Authentication

Since it's all just plain HTTP, we can use headers like we always do. Go ahead and use your favorite auth middleware that you use for the other REST endpoints.

Client

Make sure to include a polyfill in your web page code, since not all major browsers provide native support for SSE.

Try event-source-polyfill.

To connect to SSE streams from node.js, use the eventsource package.

Further reading

License

MIT