ข้ามไปเนื้อหาหลัก

fetch + ReadableStream — อ่านข้อมูลแบบ streaming

response.body เป็น ReadableStream — อ่านทีละ chunk ได้โดยไม่ต้องรอ response ทั้งหมด (เหมาะกับ AI streaming, large file download)

const response = await fetch('/api/stream');
const reader = response.body.getReader();
const decoder = new TextDecoder();

let result = '';
while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  result += decoder.decode(value, { stream: true });
  console.log('chunk:', decoder.decode(value));
}

SSE-style streaming (AI responses):

async function streamChat(prompt) {
  const res = await fetch('/api/chat', {
    method: 'POST',
    body: JSON.stringify({ prompt }),
  });

  const reader = res.body.getReader();
  const decoder = new TextDecoder();

  for await (const chunk of readChunks(reader)) {
    const text = decoder.decode(chunk);
    appendToUI(text);  // render ทีละ token
  }
}

async function* readChunks(reader) {
  while (true) {
    const { done, value } = await reader.read();
    if (done) return;
    yield value;
  }
}

ใช้ response.body.pipeThrough(new TextDecoderStream()) เพื่อ decode โดยไม่ต้องทำเอง — API สะอาดกว่าถ้าไม่ต้องการ control granular