@server-sent-stream/web
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

@server-sent-stream/web

This package allows you to consume server-sent events through the Web Streams API. This lets you use them through e.g. the fetch API.

Usage

This package can be used as an ESM or CommonJS module:

import EventSourceStream from '@server-sent-stream/web';
const EventSourceStream = require('@server-sent-stream/web');

The EventSourceStream implements the TransformStream interface. It consumes a stream of Uint8Arrays (like the kind that the fetch API returns), and produces a stream of MessageEvents.

Here's an example of how it can be used with the fetch API:

// Fetch some URL that returns an event stream
const response = await fetch('https://example.com/events', {body: '...'});

// Pipe the response body into an EventSourceStream
const decoder = new EventSourceStream();
response.body.pipeThrough(decoder);

// Read from the EventSourceStream
const reader = decoder.readable.getReader();

while (true) {
    const {done, value} = await reader.read();
    if (done) break;

    // The value will be a `MessageEvent`.
    console.log(value);
    // MessageEvent {data: 'message data', lastEventId: '', …}
}

Limitations

There are a couple things that the EventSource API does and this doesn't:

  • Reconnection does not occur, and retry events are ignored.
  • The origin attribute of the emitted MessageEvents is not set.

Related packages

If you want a streaming interface for Node's stream API, see @server-sent-stream/node. For just the event stream parser, see @server-sent-stream/parser.

Package Sidebar

Install

npm i @server-sent-stream/web

Weekly Downloads

6,821

Version

1.0.3

License

ISC OR MIT OR Apache-2.0

Unpacked Size

8.03 kB

Total Files

9

Last publish

Collaborators

  • valadaptive