생활코딩/node.js

node.js를 이용하여 홈페이지 만들기. 중간정리 및 코드

7he8oy 2020. 12. 31. 21:17
var http = require('http');
var fs = require('fs');
var url = require('url');

function templateHTML(t,l,body){
  return template = `
  <!doctype html>
  <html>
  <head>
    <title>민석 - ${t}</title>
    <meta charset = "utf-8">
  </head>
  <body>
    <h1><a href = '/' >홈</a></h1>
    ${l}
    <a href = "/create">create</a>
    ${body}
  </body>
  </html>
  `;
}

function templatelist(filelist){
  var list = '<ol>';
  var i = 0;
  while(i<filelist.length){
    list = list + `<li><a href = ./?id=${filelist[i]}>${filelist[i]}</a></li>`;
    i = i+1;
  }
  list = list + '</ol>'
  return list;
}

var app = http.createServer(function(request,response){
    var _url = request.url;
    var queryData = url.parse(_url, true).query;
    var title = queryData.id;
    var pathname = url.parse(_url, true).pathname;

    //으앙 이거는 지금 맨 첫 if는 pathname이 '/'인지 아닌지로 not found를 출력할 페이지를 구분.
    //그 다음 if로는 queryData.id가 존재하지 않는 것은 mainpage로 인식한 것임.
    if(pathname ==='/'){
      if(queryData.id === undefined){
          fs.readdir('./data', function(err, filelist){
            var title = 'Wellcome';
            var description = 'hihi';
            var list = templatelist(filelist);
            var template = templateHTML(title,list,`<h1>${title}</h1><p>${description}</p>`)
            response.writeHead(200);
            response.end(template);
          })
      } else {
        fs.readdir('./data', function(err, filelist){
          fs.readFile(`data/${title}`, 'utf8', function(err, description){
            var list = templatelist(filelist)
            var title = queryData.id
            var template = templateHTML(title,list,`<h1>${title}</h1><p>${description}</p>`)
            response.writeHead(200);
            response.end(template);
         });
       });
      }
    } else if (pathname === '/create'){
      fs.readdir('./data', function(err, filelist){
        fs. readFile('syntax/form.html', function(err, form){
          var title = '민석 - create';
          var description = 'wirte what you want'
          var list = templatelist(filelist);
          console.log(list)
          var template = templateHTML(title,list,`<h1>${title}</h1><p>${description}</p><p>${form}</p>`)
          response.writeHead(200);
          response.end(template);
      });
    });
    } else {
      response.writeHead(404);
      response.end('Not found');
    }

});
app.listen(4000);

아직 미약하지만 그래도 처음으로 홈페이지를 만들었다. 

 

이 홈페이지는 templateHTML 함수에 의해 홈페이지의 개략적인 틀을 결정하고,

templatelist 함수에 의해 페이지 리스트를 동적으로 생성한다.

그리고 query string에 따라 data디렉토리에서 알맞은 파일을 불러오고 그 파일 내의 본문을 홈페이지에 띄우는 형태다. 

 

첫 번째 if는 pathname === ' /  '인 것과 /create 인것, 어느 것도 아닌 것을 구분한다.

/create이라면 이것은 서버에 접속하는 사람들로부터 데이터를 받는 페이지다. 

어느 것도 아닌 것은 notfound를 전달한다.

 

두번째 if는 pathname ==='/'인 것들 중에서 querydata가 존재하는 것과 그렇지 않은 것을 구분한다.

 존재하는 것은 홈 이외의 본문을 갖고 있는 페이지이며,

존재하지 않는 것은 홈페이지다.

 

'생활코딩 > node.js' 카테고리의 다른 글

객체란?  (0) 2021.01.02
홈페이지 완성  (0) 2021.01.02
동기와 비동기 그리고 콜백  (0) 2020.12.31
동적으로 웹사이트 다루기!  (0) 2020.12.30
URL의 이해  (0) 2020.12.30