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

h3-sse

v0.0.12

Published

Server sent event utilities for the H3 http framework

Downloads

119

Readme

H3 SSE

H3 utilities for server sent events

Table of Contents

Installation

npm install h3-sse
pnpm install h3-sse

Basic Usage

import { eventHandler } from 'h3';
import { createEventStream, sendEventStream } from 'h3-sse';

eventHandler((event) => {
    const eventStream = createEventStream(event);

    // send a message every second
    const interval = setInterval(async () => {
        await eventStream.push('hello world');
    }, 1000);

    // cleanup when the connection is closed
    eventStream.onClose(async () => {
        clearInterval(interval);
    });

    // send the stream to the client
    await eventStream.send();
});

It's important to note that sendEventStream() must be called before you can start pushing messages. So if you want to send an initial message you would have to do it like so.

eventHandler(async (event) => {
    const eventStream = createEventStream(event);

    // this must be called before pushing the first message;
    // additionally this should NOT be awaited because it will block everything until the stream is closed
    eventStream.send();
    await eventStream.push('hello world');

    const interval = setInterval(async () => {
        await eventStream.push('hello world');
    }, 1000);

    eventStream.onClose(async () => {
        clearInterval(interval);
    });
});

Autoclose Parameter

By default EventStreams will automatically be closed when the request has been closed by either the client or the server. If you wish to change this behavior you can set autoclose to false like so:

const eventStream = createEventStream(event, { autoclose: false });

This means if you want to close the stream after a connection has closes you will need to listen to it yourself:

const eventStream = createEventStream(event, { autoclose: false });

event.node.req.on('close', async () => {
    await eventStream.close();
});

Advanced Messages

eventStream.push() accepts a string or an EventStreamMessage

When sending a string the input will be placed into the "data" field.

When sending EventStreamMessage you are able to send additional metadata such as an eventId and eventName. However the main data should be placed in the "data" field. For info on what all of these fields do please read here

// this
await eventStream.push('hello world');
// is equivalent to this
await eventStream.push({
    data: 'hello world',
});

// however the EventStreamMessage let's you add additional metadata fields
await eventStream.push({
    id: '1', // the event id
    event: 'message' // the event name. When blank the client assumes this is "message"
    data: 'hello world',
    retry: 200, // how long the client should wait before trying to reconnect

});

If you want to send an object you must first serialize it to a string.

const user = {
    id: '1',
    name: 'john doe',
    email: '[email protected]',
};
// without metadata
await eventStream.push(JSON.stringify(user));

// with metadata
await eventStream.push({
    data: JSON.stringify(user),
});

Accessing Last Event ID

For details about this header see here.

const eventStream = createEventStream(event);
eventStream.lastEventId; // string | undefined;

Closing the Stream and Connection

Calling eventStream.close() will close the stream and if the stream has been handed to the client it will also close the connection.

eventHandler((event) => {
    const eventStream = createEventStream(event);
    // send 10 messages then close the stream and connection
    let msgCount = 0;
    setInterval(async () => {
        msgCount++;
        await eventStream.push(`hello world ${msgCount}`);
        if (msgCount >= 10) {
            clearInterval(interval);
            await eventStream.close();
        }
    }, 1000);
    await eventStream.send();
});

Be aware that spec compliant SSE clients will auto-reconnect when the connection is closed. To get around this you can send a "done" or "finished" event and then add logic to the client application to stop reconnecting.

eventHandler((event) => {
    const eventStream = createEventStream(event);
    let msgCount = 0;
    setInterval(async () => {
        msgCount++;
        await eventStream.push(`hello world ${msgCount}`);
        if (msgCount >= 0) {
            // send some kind of "finished" 'event
            // then add logic to the client to stop
            await eventStream.push('done');
            // alternative
            await eventStream.push({
                event: 'done',
                data: 'No more data',
            });
            // cleanup
            clearInterval(interval);
            await eventStream.close();
        }
    }, 1000);
    await eventStream.send();
});