ReadableStream 활용하기

웹 개발/Study 2024. 5. 24. 11:21

ReadableStream은 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

 

ReadableStreamBYOBReader: read() method - Web APIs | MDN

The read() method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. A request for data will be satisfied from the stream's internal queues if there is any data pres

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/getReader

 

ReadableStream: getReader() method - Web APIs | MDN

The getReader() method of the ReadableStream interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/API/WritableStream/getWriter

 

WritableStream.getWriter() method - Web APIs | MDN

The getWriter() method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released.

developer.mozilla.org

 

https://stackoverflow.com/questions/67376362/what-is-the-difference-between-createreadstream-and-readable-class

 

What is the difference between "createReadStream" and "Readable" class?

Can someone explaint Difference between createReadStream and readable in node.js? By my observes they are similar, so what is under the hood difference, and when should each be used? for example co...

stackoverflow.com

https://web.dev/articles/streams

 

Streams - 최종 가이드  |  Articles  |  web.dev

Streams API를 사용하면 JavaScript가 네트워크를 통해 수신된 데이터 스트림에 프로그래밍 방식으로 액세스하여 원하는 대로 처리할 수 있습니다.

web.dev

 

'웹 개발 > 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
: