ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [생활코딩] Node.js 강의 7일차
    Node.js 2021. 6. 29. 22:28

    강의 내용 

    객체 : 서로 연관된 데이터와 데이터를 처리하는 방법인 함수를 그룹핑해서 코드의 복잡성을 낮추는 수납상자

     

    +) 
    객체를 구성하는 멤버의 값은 어떤 것이라도 될 수 있다. 아래 person 객체는 문자열, 숫자, 배열 두개와 두개의 함수를 가지고 있다. 처음 4개의 아이템은 데이터 아이템으로, 객체의 프로퍼티(속성) 라고 부른다. 끝에 두개의 아이템은 함수로, 데이터를 가지고 뭔가 일을 할 수 있게 되며 메소드 라고 부릅니다. 객체의 프로퍼티와 메소드는 점표기법을 통해 호출한다. 
    'this' 키워드는 지금 동작하고 있는 코드를 가지고 있는 객체를 가르킨다. 객체 멤버의 컨텍스트가 바뀌는 경우에도 언제나 정확한 값을 사용하게 해준다.(예를 들어, 두개의 다른 person 객체가 각각 다른 이름으로 인스턴스로 생성된 상태에서 인사말을 출력하기 위해 객체의 name 을 참조해야 할때 )

    출처 : Mozilla Javasciprt 객체 기본 (https://developer.mozilla.org/ko/docs/Learn/JavaScript/Objects/Basics)

    var person = {
      name: ['Bob', 'Smith'],
      age: 32,
      gender: 'male',
      interests: ['music', 'skiing'],
      bio: function() {
        alert(this.name[0] + ' ' + this.name[1] + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');
      },
      greeting: function() {
        alert('Hi! I\'m ' + this.name[0] + '.');
      }
    };

    그 전에 썼던 templateHTML, templateList 함수를 객체로 만들어주고 template.list() , template.html()로 호출해줬다. 

    var template = {
      html: function(title,list,body,control){
        return ` 
        <!doctype html>
        <html>
        <head>
          <title>WEB- ${title}</title>
          <meta charset="utf-8">
        </head>
        <body>
          <h1><a href="/">WEB</a></h1>
          ${list}
          ${control}
          ${body}
        </body>
        </html>
      `;
      },
      list : function(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 list = template.list(filelist);
    //var html = template.html(title,list,`<h2>${title}</h2>${description}`,
    //          `<a href ="/create">create</a>`);

     

    강의 코드

    var http = require('http');
    var fs = require('fs');
    var url = require('url');
    var qs = require('querystring');
    
    
    var template = {
      html: function(title,list,body,control){
        return ` 
        <!doctype html>
        <html>
        <head>
          <title>WEB- ${title}</title>
          <meta charset="utf-8">
        </head>
        <body>
          <h1><a href="/">WEB</a></h1>
          ${list}
          ${control}
          ${body}
        </body>
        </html>
      `;
      },
      list : function(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 = template.list(filelist);
              var html = template.html(title,list,`<h2>${title}</h2>${description}`,
              `<a href ="/create">create</a>`);
              response.writeHead(200);
              response.end(html);
            })
          }else{
            fs.readdir('./data',function(error,filelist){
              fs.readFile(`data/${queryData.id}`,'utf8',function(err,description){
                var title = queryData.id;
                var list = template.list(filelist);
                var html= template.html(title,list,`<h2>${title}</h2>${description}`,
                `<a href ="/create">create</a>
                <a href="update?id=${title}">update</a>
                <form action="/delete_process" method="post" >
                  <input type="hidden" name ="id"  value="${title}">
                  <input type="submit" value="delete">
                </form>`);
                response.writeHead(200);
                response.end(html);
              });
            });
          }
        } else if(pathname==='/create'){
            fs.readdir('./data',function(error,filelist){
              var title = 'Web - create';
              var list = template.list(filelist);
              var html = template.html(title,list,`
              <form action="/create_process" method="post">
              <p><input type="text" name="title" placeholder="text"></p>
              <p>
                <textarea name="description" placeholder="description"></textarea>
              </p>
              <p>
                <input type="submit">
              </p>
            </form>
              `,'');
              response.writeHead(200);
              response.end(html);
            });
        }else if(pathname==='/create_process'){
          var body = '';
          request.on('data',function(data){
              body = body + data;
          });
          request.on('end',function(){
            var post = qs.parse(body);
            var title = post.title;
            var description = post.description;
            fs.writeFile(`data/${title}`,description,'utf8',
            function(err){
              response.writeHead(302,{Location:`/?id=${title}`});
              response.end();
            })
          });
          
        }else if(pathname==='/update'){
          fs.readdir('./data',function(error,filelist){
            fs.readFile(`data/${queryData.id}`,'utf8',function(err,description){
              var title = queryData.id;
              var list = template.list(filelist);
              var html= template.html(title,list,
                ` 
                <form action="/update_process" method="post">
                <input type="hidden" name="id" value="${title}">
                <p><input type="text" name="title" placeholder="text" value ="${title}"></p>
                <p>
                  <textarea name="description" placeholder="description">${description}</textarea>
                </p>
                <p>
                  <input type="submit">
                </p>
              </form>
              `
              ,
              `<a href ="/create">create</a> <a href="update?id=${title}">update</a>`);
              response.writeHead(200);
              response.end(html);
            });
          });
        }else if(pathname==='/update_process'){
          var body = '';
          request.on('data',function(data){
              body = body + data;
          });
          request.on('end',function(){
            var post = qs.parse(body);
            var id = post.id;
            var title = post.title;
            var description = post.description;
            console.log(post);
            //파일 이름 바꾸기
            fs.rename(`data/${id}`,`data/${title}`,function(error){
              //바뀐 내용 버꾸기
              fs.writeFile(`data/${title}`,description,'utf8',
              function(err){
                response.writeHead(302,{Location:`/?id=${title}`});
                response.end();
              })
            })
          });
        }else if(pathname==='/delete_process'){
          var body = '';
          request.on('data',function(data){
              body = body + data;
          });
          request.on('end',function(){
            var post = qs.parse(body);
            var id = post.id;
            fs.unlink(`data/${id}`,function(error){
              response.writeHead(302,{Location:`/`});
              response.end();
            })
          });
        }
        else {
            response.writeHead(404);
            response.end('Not found');
          }
    });
    app.listen(3000);
Designed by Tistory.