Web Streams-compatible TransformStream for server-sent events
npm install @server-sent-stream/webThis package allows you to consume server-sent events through the Web Streams API. This lets you use them through e.g. the fetch API.
This package can be used as an ESM or CommonJS module:
``js`
import EventSourceStream from '@server-sent-stream/web';
`js`
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:
`js
// 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: '', …}
}
There are a couple things that the EventSource API does and this doesn't:retry
- Reconnection does not occur, and events are ignored.origin
- The attribute of the emitted MessageEvent`s is not set.