Node.js 함수를 활용한 코드 정리(7)

Sunny Kim·2020년 9월 29일
0

node.js

목록 보기
8/16

html 함수를 사용하여 코드 정리

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>
  `;
}
  1. 재사용할 수 있도록 함수를 정의
  2. 기존의 html 부분은 지워주고 함수를 넣어준다.
var template = templateHTML(title, list, `<h2>${title}</h2>${data}`)

list 함수를 사용하여 코드 정리

function templateList(filelist){
  var list = '<ul>';
  var  i = 0;
  while(i < filelist.length){ // filelist의 엘리먼트 갯수만큼 반복
    list = list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
    i = i+1;
  }
  list = list + '</ul>';
  return list;
}
var list = templateList(filelist);

전체코드

var http = require('http');
var fs = require('fs');
var url = require('url'); // url이라는 모듈을 사용할 것이다라고 알려주는 것

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){ // filelist의 엘리먼트 갯수만큼 반복
    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; // 위의 모듈 url과 구별하기 위해 _url로 변경
    var queryData = url.parse(_url, true).query;
    var pathname = url.parse(_url, true).pathname;

    console.log(pathname);
    // if(_url == '/'){
    //   title='Welcome';
    // }
    // if(_url == '/favicon.ico'){
    //   return response.writeHead(404);
    // }
    response.writeHead(200);
    //쿼리스트링에 따라 파일명 생성
    if(pathname === '/'){
      
      if(queryData.id === undefined){ // 쿼리스트링이 없는 경우 출력될 내용
        // 추가 한 부분
          console.log(filelist);
          var title = 'Welcome';
          var data = 'Hello, Node.js';
          /* 참조용
          var list =`
            <ol>
              <li><a href="/?id=HTML">HTML</a></li>
              <li><a href="/?id=CSS">CSS</a></li>
              <li><a href="/?id=JAVASCRIPT">JavaScript</a>			</li>
            </ol>`
            */
          
          var list = templateList(filelist);

          var template = templateHTML(title, list, `<h2>${title}</h2>${data}`)
          response.writeHead(200); // 200은 성공
          response.end(template);
      // id값이 있는 값의 코드 
      }else{
        fs.readdir('./data', function(error, filelist){
          console.log(error);
          // 파일 읽기
          fs.readFile(`data/${queryData.id}`, 'utf-8',function(err, data){
          var title = queryData.id;
          var list = templateList(filelist);
          var template = templateHTML(title, list, `<h2>${title}</h2>${data}`)
          response.writeHead(200); // 200은 성공
          response.end(template); 
        });
      });
  }
  }else{
    response.writeHead(400);
    response.end('Not found'); 
  }
});
app.listen(3000);
profile
풀스택개발자를 목표로 공부중

0개의 댓글

관련 채용 정보