본문 바로가기

WEB

[WEB] WEB2 - Node.js (3)

확실히 WEB1이랑은 볼륨이 확 차이나는 것 같다... :0


JavaScript 문법  

  • 반복문
console.log('A');
console.log('B');

var i = 0;
while(i < 2){
  console.log('C1');
  console.log('C2');
  i = i + 1;
}

console.log('D');
/*결과값: A B C1 C2 C1 C2 D*/

 

  • 배열 자료형
var arr = ['A','B','C','D'];
console.log(arr[1]);
console.log(arr[3]);
arr[2] = 3;
console.log(arr);
console.log(arr.length);
arr.push('E');
console.log(arr);

/*결과값 B D [A, B, 3, D] 4 [A, B, 3, D, E]*/

- arr.length :: 배열의 길이

- arr.push() :: 배열 삽입

 

+) 배열 & 반복문

var number = [1,400,12,34];
var i = 0;
var total = 0;
while(i < number.length){
  total = total + number[i];
  i = i + 1;
}
console.log(`total : ${total}`);
/*total : 447*/

 

  • 함수
function f123(){
  console.log(1);
  console.log(2);
  console.log(3);
  console.log(4);
}

- 함수 이용의 장점: 유지보수가 간편해짐!

 

/*Math.round : 반올림 해주는 함수*/
console.log(Math.round(1.6)); //2
console.log(Math.round(1.4)); //1
/*결과값: 2 1 */ 
 
function sum(first, second){ // parameter(매개체)
  console.log(first+second);
}
 
sum(2,4); // argument(인자)
/*결과값: 6*/

- 인자(argument) : 함수에 전달하는 것

- 매개체(parameter) : 인자를 받아서 함수 안으로 전달해주는 것

 

function sum(first, second){ // parameter
  return first+second;
}
 
console.log(sum(2,4)); // argument

ㄴ 다른 컴퓨터 언어와 똑같이 JavaScript에서도 함수의 return 값을 전달하도록 할 수 있다. 

 

Node.js

  • 현재 디렉토리에서 파일 목록 알아내기
var testFolder = './data'; // './' <- 는 현재 디렉토리! 라는 뜻. 생략해도 되지만 쓰는게 더 명확
var fs = require('fs');
 
fs.readdir(testFolder, function(error, filelist){
  console.log(filelist); //배열로 출력, readdir:는 파일목록을 배열로 처리한다.
})

fs.readdir 는 파일 목록을 배열로 처리해주는 명령어이다.

 

이걸 이용하면 main 파일의 로직 변경 없이 파일을 자유롭게 추가하고, 수정할 수 있게 된다. 이렇게 되면 훨씬 간편할 뿐만 아니라 변경점이 있을 때마다 서버를 끄고 켤 필요가 없어진다.

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>
          `;
          response.writeHead(200);
          response.end(template);
        })

 

함수를 이용해서 이제까지 계속 작성해오던 코드에서 중복인 부분을 생략하고, 훨씬 융통성 있게 정리할 수 있다.

 

  • 정의한 함수
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){
    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 template = templateHTML(title, list, `<h2>${title}</h2>${description}`);
response.writeHead(200);
response.end(template);

 


여기까지 했던 것을 다 적용해서 짠 main코드

더보기

 

var http = require('http');
var fs = require('fs');
var url = require('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){
    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 = templateList(filelist);
          var template = templateHTML(title, list, `<h2>${title}</h2>${description}`);
          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;
            var list = templateList(filelist);
            var template = templateHTML(title, list, `<h2>${title}</h2>${description}`);
            response.writeHead(200);
            response.end(template);
          });
        });
      }
    } else {
      response.writeHead(404);
      response.end('Not found');
    }



});
app.listen(3000);
적용한 사이트 화면!

 

▽생활코딩

'WEB' 카테고리의 다른 글

[WEB] WEB2 - Node.js (5)  (0) 2021.04.16
[WEB] WEB2 - Node.js (4)  (0) 2021.04.14
[WEB] WEB2 - Node.js (2)  (0) 2021.04.09
[WEB] WEB2 - Node.js (1)  (0) 2021.04.08
[WEB] WEB1 - HTML & Internet(2)  (0) 2021.04.02