lukeed/fetch-event-stream
关于
A tiny (741b) utility for Server Sent Event (SSE) streaming via `fetch` and Web Streams API
网站与应用实测星标增长
- 24小时
- 0
- 7天
- 0
- 15天
- 正在收集历史
- 1个月
- 正在收集历史
各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。
README.md
原文fetch-event-stream

A tiny (741b) utility for Server Sent Event (SSE) streaming via
fetchand Web Streams API
- Allows any HTTP method
- Built with native Web Streams API
- Works with browser, Node.js, Cloudflare Workers, Deno, and Bun
- Supports WebWorker or Service Worker environments
- Accepts
AbortControllerfor cancellable streams
Why?
Even though
EventSourceexists in browsers (and Deno!), it only sendsGETrequests and does not allow for custom HTTP headers. Most APIs (eg, Anthropic, OpenAI) requirePOSTrequests with anAuthorizationheader and a JSON payload.Web Streams are new, not very well understood, and are sometimes confused with NodeJS Streams. Because of this, many other libraries embed large polyfills or manually reconstruct desired behaviors through non-standard approaches. These polyfills are generally not necessary anymore, but still make large impacts on SDK size; for example,
openaiis17kB(gzip).
Install
$ npm install --save fetch-event-stream
Usage
import { events, stream } from 'fetch-event-stream';
// or
import { events, stream } from 'https://deno.land/x/fetch_event_stream';
API
events(res, signal?)
Convert a Response body containing Server Sent Events (SSE) into an Async Iterator that yields
ServerSentEventMessage objects.
Example
// Optional
let abort = new AbortController();
// Manually fetch a Response
let res = await fetch('https://...', {
method: 'POST',
signal: abort.signal,
headers: {
'api-key': 'token <value>',
'content-type': 'application/json',
},
body: JSON.stringify({
stream: true, // <- hypothetical
// ...
}),
});
if (res.ok) {
let stream = events(res, abort.signal);
for await (let event of stream) {
console.log('<<', event.data);
}
}
res
Type: Response
The Response to consume. Must contain a body that follows the Server-Sent Event message protocol.
signal
Type: AbortSignal
Optional. Use the AbortController interface to stop iteration. The stream will be destroyed.
stream(input, init?)
Convenience function that will fetch with the given arguments and, if ok, will return the events async iterator.
Note: Accepts the same arguments as
fetchbut does not return aResponse!
Important: Will
throwtheResponseif received non-2xxstatus code.
Example
// NOTE: throws `Response` if not 2xx status
let events = await stream('https://api.openai.com/...', {
method: 'POST',
headers: {
'Authorization': 'Bearer <token>',
'Content-Type': 'application/json',
},
body: JSON.stringify({
stream: true,
// ...
}),
});
for await (let event of events) {
console.log('<<', JSON.parse(event.data));
}
input
Type: Request | URL | string
Refer to fetch#resource documentation.
init
Type: RequestInit
Refer to fetch#options documentation.
License
MIT © Luke Edwards
探索相关项目
加载中…