Web

[Backend] Express send(), write() 차이

ㅋ. ㅋ 2024. 1. 8. 16:45

# send()

- express 프레임워크에만 있음

- content-type header 자동설정

- utf-8 자동설정

- JSON, HTML 등 다양한 데이터 형식으로 전송 가능

- 한 fetch에 대해 한번만 호출 가능

- 일반적으로 많이 사용

- write + end의 느낌

 

# write()

- end() 호출 전 까지 여러번 호출하여 데이터 조각 보내기 가능

    - 백엔드에서 단계별 응답을 프론트에 보여주기 용이 (로딩바 21/100, 62/100, 83/100, ... 과 같이)

    - 스트리밍데이터, 대용량 파일처리에 유리 (데이터가 크면 알아서 조각내서 보냄 -> 클라이언트에서 조각 합치는 로직 필요)

- string 형식으로 전송 가능

- client에 Unit8Array 형식으로 받음, decode 해야함

// 예시
res.setHeader('Content-Type', 'text/plain;charset=utf-8'); // 헤더 설정해주는 것이 좋음

setTimeout(() => {
    res.write(JSON.stringify({ step: "1/3 - Step 1 completed\n" }));
}, 2000);

setTimeout(() => {
    res.write(JSON.stringify({ step: "2/3 - Step 2 completed\n" }));
}, 3000);
  
setTimeout(() => {
    res.write(JSON.stringify({ step: "3/3 - Step 3 completed\n" }));
}, 4500);

setTimeout(() => {
	res.end(JSON.stringify({ data: "success" })); // end에도 데이터 실어보낼 수 있음
}, 7000);

위 코드는 백엔드에 데이터 요청하면

2초 뒤에 응답을 보내줘서 1/3 - Step 1 completed를 찍을 수 있음

3초 뒤엔  2/3 - Step 2 completed를 찍을 수 있고~

// frontend 코드
fetch('/processing')
  .then(response => {
    const reader = response.body.getReader();
    const processStream = async () => {
      while (true) {
        const { done, value } = await reader.read();
        if (done) {
          break;
        }
        const text = new TextDecoder().decode(value);
        console.log(text);
      }
    };
    processStream();
  })
  .catch(error => console.error('Error:', error));

 

약간 소켓 통신처럼 응답 열린 순간부터 뭔가 처리되면 하나씩 순차적으로 보내고 엔드로 닫는 느낌?

프론트 입장에서는 응답이 json이 아닌 Unit8Array로 오고 디코딩 해도 스트링이라 다시 파싱하는 귀찮음이 있긴함

'Web' 카테고리의 다른 글

[Frontend] Cache의 간단한 이해  (0) 2024.03.07
[Frontend] 이미지 최적화  (0) 2024.03.06
[Backend] Node.js + Express MVC 기초 세팅  (1) 2024.01.02
[Frontend] JS/TS 체인/루프 구현  (0) 2023.11.06
[Backend] Django MTV중 TV 해보기  (1) 2023.10.14