처음부터 차근차근

Node.js 함수를 이용해서 main.js 정리정돈하기 본문

FrameWork/Node.js

Node.js 함수를 이용해서 main.js 정리정돈하기

HangJu_95 2023. 5. 30. 14:20
728x90

반복되는 코드는 함수를 이용하여 정리해 줄 수 있다.

 

현재 두 부분의 코드가 반복해서 보이는데

templateHTML, templateList를 통해 정리해보자.

 

function templateHTML(title, list, body){
  return `
  <!doctype html>
  <html>
  <head>
    <title>WEB1 - ${title}</title>
    <meta charset="utf-8">
  </head>
  <body>
    <h1><a href="/">WEB</a></h1>
    ${list}
    ${body}
  </body>
  </html>
  `;
}
function templateList(filelist){
  var list = '<ul>';
  var i = 0;
  while(i < filelist.length){
    list = list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
    i = i + 1;
  }
  list = list+'</ul>';
  return list;
}

함수를 정리해 준 모습이다.

 

var app = http.createServer(function(request,response){
    var _url = request.url;
    var queryData = url.parse(_url, true).query;
    var pathname = url.parse(_url, true).pathname;
    if(pathname === '/'){
      if(queryData.id === undefined){
        fs.readdir('./data', function(error, filelist){
          var title = 'Welcome';
          var description = 'Hello, Node.js';
          var list = templateList(filelist);
          var template = templateHTML(title, list, `<h2>${title}</h2>${description}`);
          response.writeHead(200);
          response.end(template);
        })
      } else {
        fs.readdir('./data', function(error, filelist){
          fs.readFile(`data/${queryData.id}`, 'utf8', function(err, description){
            var title = queryData.id;
            var list = templateList(filelist);
            var template = templateHTML(title, list, `<h2>${title}</h2>${description}`);
            response.writeHead(200);
            response.end(template);
          });
        });
      }
    } else {
      response.writeHead(404);
      response.end('Not found');
    }
 
 
 
});
app.listen(3000);

함수를 정리해줬더니, 본문 코드가 굉장히 깔끔해졌다.

'FrameWork > Node.js' 카테고리의 다른 글

Node.js App에서 Create 진행해보기  (0) 2023.05.31
Node.js Synchronous & Asynchronous  (0) 2023.05.30
Node.js 파일 리스트 읽어오기  (0) 2023.05.30
Node.js 홈페이지 구현  (0) 2023.05.30
Node.js Not found 구현  (0) 2023.05.30