본문 바로가기

내일 배움 캠프/그땐 (응답하라 추억시대)

프론트엔드 연결 리팩토링

728x90

이전에는 파일 하나당 하나씩 분기를 해서 처리했었는데

이제 url 뒤의 확장자를 체크해서 프론트엔드 파일이면 함수로 넘겨 주고

함수 안에서는 /를 제외하고는 각자 파일을 찾아갈 수 있게 하였다. 

 

이전 app.js if문 분기

 if (pathname == '/' || pathname == '/main') {
          frontconnection(pathname, res);
        }

 

이전 fontendconnection.js

import fs from 'fs';

function frontconnection(pathname, res) {
  let filePath;
  if (pathname == '/main') {
    filePath = './dist/public/main.html';
  }
  if (pathname == '/') {
    filePath = './dist/public/index.html';
  }

  res.writeHead(200, { 'Content-Type': 'text/html' });
  const readStream = fs.createReadStream(filePath);
  readStream.pipe(res);
}

export default frontconnection;

 

app.js 분기 처리

if (
          pathname == '/' ||
          pathname.endsWith('.js') ||
          pathname.endsWith('.html') ||
          pathname.endsWith('.css')
        ) {
          frontconnection(pathname, res);
        }

frontconnection.js

import fs from 'fs';

function frontconnection(pathname, res) {
  let filePath;
  if (pathname == '/') {
    filePath = './dist/public/index.html';
  } else {
    filePath = `./dist/public${pathname}`;
  }

  res.writeHead(200, { 'Content-Type': 'text/html' });
  const readStream = fs.createReadStream(filePath);
  readStream.pipe(res);
}

export default frontconnection;