핵심적으로 중요한 것은, Stream에서 데이터를 읽어오면 stream에는 원래 그 데이터는 더 이상 남아있지 않다는 것임. 마치 강가(stream)에서 바가지로 물을 퍼올려서 라면 끓이는 데 쓰면, 강가에 바로 그 물은 더 이상 남아있지 않은 것과 비슷함.
new ReadableStream()으로 만들어야 함.const readableStream = new ReadableStream({
start(controller) {
},
pull(controller) {
},
cancel(reason) {
}
});
const readableStream = new ReadableStream({
start(controller) {
// 스트림이 생성될 때 초기화 작업 수행
console.log('스트림 시작');
controller.enqueue('첫 데이터 밀어넣음'); // 초기 데이터 푸시
}
});
const readableStream = new ReadableStream({
start(controller) {
this.counter = 0; // 스트림의 상태를 추적하기 위한 변수 설정
},
pull(controller) {
// 소비자가 데이터를 요청할 때마다 호출됨
this.counter++;
controller.enqueue(`Chunk #${this.counter}`);
// 스트림을 닫고 싶을 때
if (this.counter >= 5) {
controller.close();
}
}
});
controller.enqueue())const readableStream = new ReadableStream({
start(controller) {
this.resource = setInterval(() => {
controller.enqueue('새 데이터임');
}, 1000);
},
cancel(reason) {
console.log('스트림 이제 이거땜에 문닫았어요:', reason);
clearInterval(this.resource); // 자원 해제
}
});
출처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