Back-end/Node.js

[Node.js] 객체(Object), 모듈(Module) 사용하여 리팩토링

poppy 2020. 12. 25. 11:21
반응형

soohyun6879.tistory.com/70

 

[Node.js] 파일 수정, 삭제하기

soohyun6879.tistory.com/69 [Node.js] POST방식으로 데이터 전송하고 받기, 파일 생성, 리다이렉션 soohyun6879.tistory.com/65 [Node.js] 파일 목록 알아내기 / 반목문과 함수를 사용하여 중복 제거하기 파일 목..

soohyun6879.tistory.com

이전 포스팅에 이어서 객체와 모듈을 사용하여 코드를 더 깔끔하게 정리하기 위해 리팩토링을 해보겠습니다.

 

객체를 사용하여 리팩토링

var template = {
  HTML:function(title, list, body, control){
    return `
    <!doctype html>
    <html>
    <head>
      <title>WEB1 - ${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>`
);
response.writeHead(200);
response.end(html); //변경

함수를 값으로 사용하는 객체로 바꾸어주었으므로 함수를 호출하는 부분도 바꿔줍니다. 변경이라고 주석이 달려있는 부분이 코드가 바뀐 부분입니다. 코드의 다른 부분도 이렇게 다 바꾸어 줍니다.

 

모듈

- 모듈은 독립된 기능을 갖는 것(함수, 파일)들의 모임

var M = {
    v:'v',
    f:function(){
      console.log(this.v);
    }
  }
module.exports = M; 

이렇게 독립된 기능을 가지고 있는 객체들을 모아 따로 파일로 만들어 모듈화할 수 있습니다. 

module.exports = M; - M이라는 모듈을 외부에서도 사용할 수 있게 해준다는 의미입니다.

var part = require('./mpart.js');
part.f();

다른 파일에서 사용할 경우 require( )을 사용하여 모듈이 있는 파일을 불러온 후 원하는 기능을 호출하면 됩니다. 모듈은 기능을 분리시켜 사용할 때 유용하고, 기능을 좀 더 깔끔하게 정리할 수 있습니다.

 

모듈을 사용하여 리팩토링

module.exports = {
    HTML:function(title, list, body, control){
      return `
      <!doctype html>
      <html>
      <head>
        <title>WEB1 - ${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;
    }
  }

위에서 객체로 만들어주었던 부분을 template.js 라는 파일을 만들어 분리시켜 줍니다. 외부에서 사용가능하게 해야하므로 module.exports를 해줍니다.

var template = require('./lib/template.js');

main.js에서 모듈이 있는 파일을 불러와야 모듈을 사용할 수 있습니다.

 

전체 코드입니다.

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');
var template = require('./lib/template.js');
 
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="title"></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="title" 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;
          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);
반응형