언어&프레임워크/Node.js

함수를 이용해 코드 정리정돈하기

밍풀 2023. 1. 10. 21:12

코드의 복잡성이 높아지면 코드관리가 어려워짐

이를 위해 함수로 정리정돈할 필요 있음, 가독성이 높아지도록

완전히 똑같은 코드는 함수화 시키는 방법을 통해 가능 ; 재사용가능한 껍데기 만들기

또한 이를통해 함수의 이름으로 로직에 대한 설명이 가능해 진다는 장점도 존재함( ex. html에 대한 template인가보다)

 

함수화 시키기 전

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
var http = require('http');
var fs = require('fs');
var url = require('url');
var app = http.createServer(function(request,response){
    var _url = request.url;//사용자가 요청한 값 /?id=CSS 이런식의 쿼리스
    var queryData = url.parse(_url, true).query;//{id : 'css'}같은 객체
    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 = '<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>';
          var template = `
          <!doctype html>
          <html>
          <head>
            <title>WEB1 - ${title}</title>
            <meta charset="utf-8">
          </head>
          <body>
            <h1><a href="/">WEB</a></h1>
            ${list}
            <h2>${title}</h2>
            <p>${description}</p>
          </body>
          </html>
          `;//주소창에 쿼리스트링 부분에 /?id=min 입력시 title이 min으로 치환되어 화면나옴
          response.writeHead(200);
          response.end(template);
        })
      }else{
 
        fs.readdir('./data'function(error,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>';
       fs.readFile(`data/${queryData.id}`,'utf8',function(err,description){
        var title = queryData.id;// css 같은 딱 id부분 즉 /?id= 요자리가 title
 
          var template = `
          <!doctype html>
          <html>
          <head>
            <title>WEB1 - ${title}</title>
            <meta charset="utf-8">
          </head>
          <body>
            <h1><a href="/">WEB</a></h1>
            ${list}
            <h2>${title}</h2>
            <p>${description}</p>
          </body>
          </html>
          `;//주소창에 쿼리스트링 부분에 /?id=min 입력시 title이 min으로 치환되어 화면나옴
          response.writeHead(200);
          response.end(template);
        });
    })
  }
else{
  response.writeHead(404);
  response.end('Not Found');
}
});
app.listen(3000);
 
cs

 

공통된 부분 함수화 시킨 후

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
var http = require('http');
var fs = require('fs');
var url = require('url');
function HTMLtemplate(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 ListTemplate(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;//사용자가 요청한 값 /?id=CSS 이런식의 쿼리스
    var queryData = url.parse(_url, true).query;//{id : 'css'}같은 객체
    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 = ListTemplate(filelist);
          var template = HTMLtemplate(title, list, `<h2>${title}</h2><p>${description}</p>`);//주소창에 쿼리스트링 부분에 /?id=min 입력시 title이 min으로 치환되어 화면나옴
          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;// css 같은 딱 id부분 즉 /?id= 요자리가 title
        var list = ListTemplate(filelist);
        var template = HTMLtemplate(title, list, `<h2>${title}</h2><p>${description}</p>`);
          response.writeHead(200);
          response.end(template);
        });
    })
  }
else{
  response.writeHead(404);
  response.end('Not Found');
}
});
app.listen(3000);
 
cs

아직 공통된 부분이 남아있어보이기에  개선의 여지가 있지만 이전보다 코드의 가독성이 높아짐을 알 수 있다.!