Node.js Azure Functions 中串流 HTTP 請求與回應

本文說明如何在你的 Node.js 函式應用程式中串流 HTTP 請求與回應。 學習如何啟用串流、處理大量資料,以及處理即時 HTTP 情境。

Note

HTTP 串流需要 v4 程式設計模型。 如果你用的是 v3,請參考 升級 指南。

Overview

HTTP 串流功能讓處理大型資料、串流 OpenAI 回應、傳遞動態內容,以及支援其他核心 HTTP 場景變得更容易。 可讓您將要求資料流至 Node.js 函式應用程式中的 HTTP 端點和回應。 在您的應用程式需要透過 HTTP 進行用戶端與伺服器之間的即時交換和互動的情況下,使用 HTTP 資料流。 使用 HTTP 時,您也可以使用 HTTP 資料流來取得應用程式的最佳效能和可靠性。

先決條件

啟用資料流

請使用以下步驟,在 Azure 的函式應用程式及本地專案中啟用 HTTP 串流:

  1. 如果你打算串流大量資料,請在Azure中修改FUNCTIONS_REQUEST_BODY_SIZE_LIMIT設定。 預設允許的最大主體大小為 104857600,限制你的請求大小約為 100 MB。

  2. 針對畚箕開發,也請將 FUNCTIONS_REQUEST_BODY_SIZE_LIMIT 加入 local.settings.json 檔案

  3. 主欄位所包含的任何檔案中,將下列程式碼新增至您的應用程式。

const { app } = require("@azure/functions");

app.setup({ enableHttpStream: true });

Tip

直接使用 request.body 以獲得串流的最大效益。 像是緩衝整個身體並回傳字串這類方法 request.text() ,這就違背了串流的初衷。

資料流範例

以下範例展示了一個透過 HTTP POST 請求接收資料的 HTTP 觸發函式。 函式會將這些資料串流到指定的輸出檔:

const { app } = require("@azure/functions");
const fs = require("fs");
const path = require("path");

app.http("httpTriggerStreamRequest", {
  methods: ["POST"],
  handler: async (request, context) => {
    context.log("HTTP trigger function processed a request.");

    if (!request.body) {
      return {
        status: 400,
        body: "Request body is required"
      };
    }

    // Create a writable stream to a file
    const outputPath = path.join(__dirname, "streamed-output.txt");
    const writeStream = fs.createWriteStream(outputPath);

    try {
      // Stream the request body to the file
      const reader = request.body.getReader();
      let done = false;

      while (!done) {
        const { value, done: readerDone } = await reader.read();
        done = readerDone;
        
        if (value) {
          writeStream.write(value);
        }
      }

      writeStream.end();
      
      return {
        status: 200,
        body: "Data successfully streamed to file"
      };
    } catch (error) {
      context.log.error("Error streaming data:", error);
      return {
        status: 500,
        body: "Error processing stream"
      };
    }
  }
});

以下範例展示了一個 HTTP 觸發函式,該函式會將檔案內容串流為對 HTTP GET 請求的回應:

const { app } = require("@azure/functions");
const fs = require("fs");
const path = require("path");

app.http("httpTriggerStreamResponse", {
  methods: ["GET"],
  handler: async (request, context) => {
    context.log("HTTP trigger function processed a request.");

    const filePath = path.join(__dirname, "sample-data.txt");

    try {
      // Check if file exists
      if (!fs.existsSync(filePath)) {
        return {
          status: 404,
          body: "File not found"
        };
      }

      // Create a readable stream from the file
      const readStream = fs.createReadStream(filePath);
      
      return {
        status: 200,
        headers: {
          "Content-Type": "text/plain",
          "Transfer-Encoding": "chunked"
        },
        body: readStream
      };
    } catch (error) {
      context.log.error("Error streaming file:", error);
      return {
        status: 500,
        body: "Error streaming file"
      };
    }
  }
});

如果想看一個使用串流的現成範例應用程式,可以參考 GitHub 上的這個範例