Skip to content

Latest commit

 

History

History
48 lines (35 loc) · 1.82 KB

README.md

File metadata and controls

48 lines (35 loc) · 1.82 KB

@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.