ReadableStream 활용하기
웹 개발/Study 2024. 5. 24. 11:21ReadableStream은 fetch함수를 실행하여 얻은 response 객체의 body의 타입으로, fs 모듈에서 제공하는 클래스이며 파일을 읽고 쓰는데에 적합하다. Readable 클래스는 파일을 읽고 쓰는 필요가 없을 경우에 사용하며 메모리 위에서만 존재하고 stream 모듈에서 제공하는 클래스이다.
nodejs 환경에서 다른 서버로 부터 받은 응답을 바로 나의 클라이언트에게 전달 해주는 메서드인 pipe를 활용하기 위해, ReadableStream객체의 getReader 메서드를 통해 데이터(버퍼)를 추출해내서 Readable객체에 push를 해줘야 했다.
fetch('https://example.com', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then((response) => {
console.log('response: ', response);
if (!response.ok) throw response.body;
return response.body;
})
.then((body) => {
if (!body) return null;
const reader = body.getReader();
const stream = new Readable({
async read(this) {
const { value, done } = await reader.read();
if (done) {
this.push(null);
}
this.push(value);
},
});
//another way
// while(true){
// const {done, value} = await reader.read()
// if(done){
// stream.push(null)
// break;
// }
// stream.push(value)
// }
stream.on('data', (chunk) => {
console.log('on data chunk: ', chunk);
});
stream.pipe(res);
})
.catch((err) => {
console.log('err: ', err);
});
참고:
https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamBYOBReader/read
https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/getReader
https://developer.mozilla.org/en-US/docs/Web/API/WritableStream/getWriter
https://web.dev/articles/streams
'웹 개발 > Study' 카테고리의 다른 글
babel 과 polyfill (0) | 2022.03.02 |
---|---|
Closure, 클로저 함수 (0) | 2022.03.01 |
let, var, const 차이점 (0) | 2022.03.01 |
웹팩 dependencies 설정 (0) | 2021.08.20 |
React 기초 연습 (0) | 2021.03.25 |