deno.com

HTTP 伺服器:串流

在 Github 上編輯

一個將回應串流回用戶端的 HTTP 伺服器範例。

function handler(_req: Request): Response {
設定變數以儲存計時器 ID 和 ReadableStream。
  let timer: number | undefined = undefined;
  const body = new ReadableStream({
當串流首次建立時,啟動一個間隔,每秒發送一個包含目前時間的區塊。
    start(controller) {
      timer = setInterval(() => {
        const message = `It is ${new Date().toISOString()}\n`;
        controller.enqueue(new TextEncoder().encode(message));
      }, 1000);
    },
如果串流關閉(用戶端斷線),則取消間隔。
    cancel() {
      if (timer !== undefined) {
        clearInterval(timer);
      }
    },
  });
傳回一個以串流作為主體的回應。
  return new Response(body, {
    headers: {
      "content-type": "text/plain",
      "x-content-type-options": "nosniff",
    },
  });
}
若要在預設埠啟動伺服器,請使用處理常式呼叫 `Deno.serve`。
Deno.serve(handler);

使用 Deno CLI 在本機執行此範例

deno run --allow-net https://deno-docs.dev.org.tw/examples/scripts/http_server_streaming.ts

在 Deno Deploy playground 中試用此範例

部署

您找到需要的資訊了嗎?

隱私權政策