Node.js Azure Functions에서 HTTP 요청과 응답을 스트리밍하세요

이 글에서는 Node.js 함수 앱에서 HTTP 요청과 응답을 스트리밍하는 방법을 설명합니다. 스트리밍 활성화, 대규모 데이터 처리, 실시간 HTTP 시나리오 처리 방법을 배우세요.

메모

HTTP 스트림은 v4 프로그래밍 모델이 필요합니다. v3를 사용 중이라면 마이그레이션 가이드 를 참고해 업그레이드하세요.

Overview

HTTP 스트림 기능은 대용량 데이터 처리, OpenAI 응답 스트리밍, 동적 콘텐츠 전달 및 기타 핵심 HTTP 시나리오 지원을 쉽게 만듭니다. Node.js 함수 앱의 HTTP 엔드포인트에 대한 요청과 응답을 스트리밍할 수 있습니다. 앱에 HTTP를 통한 클라이언트와 서버 간의 실시간 교환 및 상호 작용이 필요한 시나리오에서 HTTP 스트림을 사용합니다. HTTP 스트림을 사용하면 HTTP를 사용할 때 앱에 대한 최고의 성능과 안정성을 가져올 수도 있습니다.

필수 조건

스트림 사용

다음 단계를 사용하여 Azure 및 로컬 프로젝트에서 함수 앱에서 HTTP 스트림을 사용하도록 설정합니다.

  1. 많은 양의 데이터를 스트리밍하려는 경우 Azure FUNCTIONS_REQUEST_BODY_SIZE_LIMIT 설정을 수정합니다. 기본 허용되는 최대 본체 크기는 104857600이로, 요청 크기를 약 100MB로 제한합니다.

  2. 로컬 개발의 경우 FUNCTIONS_REQUEST_BODY_SIZE_LIMIT도 추가합니다.

  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에서 이 예시를 확인해 보세요.