Skip to content

Latest commit

 

History

History
58 lines (46 loc) · 1.51 KB

stream-response.md

File metadata and controls

58 lines (46 loc) · 1.51 KB
layout description
page
Fetch API Response objects made from async generators. Build streaming HTML responses or SSE with JS sugar.

Stream Response

Fetch API Response objects made from async generators. Build streaming HTML responses or SSE with JS sugar.

Example:

  • Table of Contents {:toc .large-only}
async function* generate() {
  for await (const row of iterAllRows()) {
    yield `${row.join(',')}\n`
  }
}

router.get('/large.csv', () => new StreamResponse(generate(), { 
  headers: [['content-type', 'text/csv']] 
}))

Creating a SSE endpoint works much the same way:

async function* sse() {
  while (true) {
    await new Promise(r => setTimeout(r, 1000));
    yield 'data: hello\n\n';
  }
}

router.get('/sse', contentType(['text/event-stream']), (req, { type }) => {
  return new StreamResponse(sse(), { headers: [['content-type', type]] })
})

*[SSE]: Server Sent Events


{:style="margin: 2rem 0"}

Links: GitHub | ghuc.cc · NPM | Browse Package · deno.land | Docs {:.faded}