[Javascript] ReadableStream 기본

데이빗·2024년 8월 20일

Javascript

목록 보기
12/13

ReadableStream이 뭐임

  • ReadableStream은 자바스크립트에서 데이터를 한번에 처리하지 않고 stream 방식으로 처리하는 인터페이스임
    • 원래는 Streams API는 네트워크 요청, 파일 처리 등 대량의 데이터를 효율적으로 처리하기 위한 웹 API의 일부임. ReadableStream 외에도 WritableStream, TransformStream 등이 있음.
  • 용어를 정리해보면
    • 스트림(Stream): 데이터의 흐름. 파일, 네트워크 응답 같은 것들이 연속적으로 흘러 들어온다고 보면 됨
    • 청크(chunk): 스트림에 흘러 들어오는 데이터의 조각 조각들을 의미함

핵심적으로 중요한 것은, Stream에서 데이터를 읽어오면 stream에는 원래 그 데이터는 더 이상 남아있지 않다는 것임. 마치 강가(stream)에서 바가지로 물을 퍼올려서 라면 끓이는 데 쓰면, 강가에 바로 그 물은 더 이상 남아있지 않은 것과 비슷함.

ReadableStream의 기본기본기본 구조

1. controller

  • 말 그대로 stream을 컨트롤하는 역할을 함
    • stream에 데이터를 푸시하거나, stream 자체를 잠시 멈추거나(댐 막듯이) 할 수 있음

2. reader

  • 스트림에서 데이터를 읽는 객체임.
    • 리더는 스트림 당 하나만 설정할 수 있음.

Controller 사용법

  • 기본적으로, start, pull, cancel이라는 세 가지 메소드를 사용함.
  • 그리고 우선 readableStream 객체를 new ReadableStream()으로 만들어야 함.
const readableStream = new ReadableStream({
    start(controller) {

    },
    pull(controller) {

    },
    cancel(reason) {

    }
});

1. start

const readableStream = new ReadableStream({
    start(controller) {
        // 스트림이 생성될 때 초기화 작업 수행
        console.log('스트림 시작');
        controller.enqueue('첫 데이터 밀어넣음'); // 초기 데이터 푸시
    }
});
  • 스트림을 처음 만들 때 사용할 액션을 정의하는 곳임.
    • 초기화를 한다든지, 어떻게 작동할 것인지 사전 세팅 등을 하는 곳임.

2. pull

const readableStream = new ReadableStream({
    start(controller) {
        this.counter = 0;  // 스트림의 상태를 추적하기 위한 변수 설정
    },
    pull(controller) {
        // 소비자가 데이터를 요청할 때마다 호출됨
        this.counter++;
        controller.enqueue(`Chunk #${this.counter}`);
        
        // 스트림을 닫고 싶을 때
        if (this.counter >= 5) {
            controller.close();
        }
    }
});
  • pull은 스트림을 사용하는 주체(reader)가 데이터를 요청할 때마다 호출됨
    • 데이터를 스트림으로 푸시해주는 역할을 함(controller.enqueue())
      • 요걸 쓰면 컨트롤러에 데이터가 채워짐
    • 스트림이 데이터로 채워질 때까지 반복적으로 호출 가능.

3. cancel

const readableStream = new ReadableStream({
    start(controller) {
        this.resource = setInterval(() => {
            controller.enqueue('새 데이터임');
        }, 1000);
    },
    cancel(reason) {
        console.log('스트림 이제 이거땜에 문닫았어요:', reason);
        clearInterval(this.resource);  // 자원 해제
    }
});
  • cancel 메서드는 스트림의 소비자가 스트림을 취소할 때 호출
    • 스트림이 더 이상 필요하지 않거나 강제로 중단해야 할 때 사용한다는 것임.
    • 그래서 스트림 취소 시 필요한 정리 작업을 수행할 수 있습니다.
  • cancel의 파라미터인 (reason)은 취소의 이유를 설명해주는 값임.




출처1: https://www.daleseo.com/js-readable-stream/
출처2: https://developer.mozilla.org/en-US/docs/Web/API/ReadableByteStreamController/enqueue
출처3: https://seungtaek-overflow.tistory.com/7
출처4: https://developer.mozilla.org/ko/docs/Web/API/ReadableStream

profile
데이터 분석가

0개의 댓글