it's em!I
Denoβ€’2y agoβ€’
6 replies
it's em!

How can I flush a stream to a response?

I'm trying to stream a response but it appears that data is only sent after either a newline is written or some buffer is filled. Is there a way to manually flush the buffer?
To repro, run this with --allow-net, then observe the difference in behavior between curl http://127.0.0.1:8000/%0a and curl http://127.0.0.1:8000/%20.

const encoder = new TextEncoder();
Deno.serve((req) => {
  let interval: number;
  let i = 0;
  const sep = decodeURIComponent(new URL(req.url).pathname.slice(1))
  return new Response(
    new ReadableStream({
      start(c) {
        interval = setInterval(() => c.enqueue(encoder.encode(i++ + sep)), 1000)
      },
      cancel() {
        clearInterval(interval)
      }
    })
  )
})
Was this page helpful?