본문 바로가기
IT

stream 이해

by 내일은교양왕 2024. 5. 3.

배경

메모리보다 큰 데이터를 처리하기 위해 나온 기술

 

개념

제한된 메모리 공간에서 지속적으로 처리되고 있는 array와 같다. 

 

반쪽짜리 정보

stream이 더 빠르다?

-> 아니다. 더 느리다. 메모리가 충분하다는 전재로 본다면, 메모리가 훨씬 빠르다. 결코 메모리보다 빠르지 않다. 이유는 stream consumer 쪽에서 데이터를 처리하는 속도가 producer가 보내는 속도보다 느릴 경우 버퍼가 꽉차게 되어 잠깐 뭠춰달라고 요구하기 때문이다. pipeline이 여러개 일 수록 이런 현상은 더욱 많이 발생된다. (버퍼가 꽉찬 상태에서 데이터를 받을 경우 손실된다.)

 

테스트

400mb 정도 큰 파일 생성

const fs = require("fs")
const file = fs.createWriteStream("./big.file")

for (let i = 0; i <= 1e6; i++) {
  file.write(
    "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n"
  )
}

file.end()

 

 

memory에 파일을 올려 테스트

메모리가 갑자기 400mb 이상으로 사용하고 있는걸 확인 할 수 있다.

서비스 운영하는 서버라면 개선이 필요하다.

router.get('/', function(req, res, next) {

  fs.readFile("./big.file", (err, data) => {
    if (err) throw err

    res.end(data)
  })
});

 

 

스트림으로 테스트

메모리를 거의 사용하지 않는걸 볼 수 있다. chunk와 buffer 용량만 추가된걸 볼 수 있다.

router.get('/', function(req, res, next) {
  const src = fs.createReadStream("./big.file")
  src.pipe(res)
});

 

 

참고

https://youtu.be/edB964-YYpE?si=-XcHt-5KfJi1BKdU

https://jeonghwan-kim.github.io/node/2017/07/03/node-stream-you-need-to-know.html

'IT' 카테고리의 다른 글

[linux] lsof command  (0) 2024.06.03
[tcp] connection 개론  (0) 2024.05.10
package-lock.json  (0) 2024.05.03
npx 개념  (0) 2024.05.03
JS 빌드 툴과 SWC  (0) 2024.02.15