Module

코드를 작성하는 과정에서 코드의 길이가 길어지면 정리정돈할 필요성이 생김 - 가장 큰 도구 : module

 

nodejs/mpart.js

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

module을 생성하기 위해서 exports 전역 객체를 사용

 

muse.js

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

module을 불러오기 위해서 require( ) 메소드 사용

 

 

 

'Web > Node.js' 카테고리의 다른 글

[Node.js] object를 통해 template 정리  (0) 2020.07.31
[Node.js] 글 삭제  (0) 2020.07.31
[Node.js] 글 수정  (0) 2020.07.31
[Node.js] 글 생성  (0) 2020.07.31
[Node.js] Package Manger  (0) 2020.07.30

객체지향 프로그래밍 목적 : 코드를 깔끔하게 복잡하지 않게 정리하는것

refactoring : 과거의 코드를 효율적으로 바꾸는 것

 

object를 통해 template 정리

template라는 객체를 만들고 객체 안에서 property를 정의

 

<기존 코드>

function templateHTML(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>
  `;
}
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 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;
  }
}

 

위 template를 사용하는 부분 수정

templateList을 template.list로 변경

templateHTML을 template.HTML으로 변경하고 template라고 되어있는 변수를 html로 수정

 

예시( 주석: 기존코드)

/* var list = templateList(filelist);
          var template = templateHTML(title, list,
            `<h2>${title}</h2>${description}`,
            `<a href="/create">create</a>`
          );
          response.writeHead(200);
          response.end(template);
*/
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);

 

 

'Web > Node.js' 카테고리의 다른 글

[Node.js] Module 사용  (0) 2020.08.02
[Node.js] 글 삭제  (0) 2020.07.31
[Node.js] 글 수정  (0) 2020.07.31
[Node.js] 글 생성  (0) 2020.07.31
[Node.js] Package Manger  (0) 2020.07.30

삭제버튼 구현

control 부분에 삭제 할 수 있는 버튼을 추가 

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}`,
              ` <a href="/create">create</a>
                <a href="/update?id=${title}">update</a>
                <a href="/delete?id=${title}">delete</a>`
            );
            response.writeHead(200);
            response.end(template);
          });
        });
      }
    } 

글을 삭제 할 때, 따로 보여줄 페이지가 없기 때문에 링크는 필요하지 않음

따라서 form 태그로 지울 id값을 가지고 delete_process로 넘어가야함

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}`,
              ` <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(template);
          });
        });
      }
    }

 

글 삭제 기능 완성(삭제 요청 처리)

delete_process 

"node.js delete file" - 검색 결과 중 아래 사진 참고

post 방식으로 받아온 id 값으로 지우고자 하는 경로를 fs.unlink()에 넣고 그 다음으로 넘어갈 페이지를 정해줌

fs.unlink( ){ } 안에 response.writeHead(302,넘어갈 페이지) 입력

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();
          })
      });
    } 

 

<전체 코드>

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');
 
function templateHTML(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>
  `;
}
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}`,
            `<a href="/create">create</a>`
          );
          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}`,
              ` <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(template);
          });
        });
      }
    } else if(pathname === '/create'){
      fs.readdir('./data', function(error, filelist){
        var title = 'WEB - create';
        var list = templateList(filelist);
        var template = templateHTML(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(template);
      });
    } 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 = templateList(filelist);
          var template = templateHTML(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(template);
        });
      });
    } 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);

'Web > Node.js' 카테고리의 다른 글

[Node.js] Module 사용  (0) 2020.08.02
[Node.js] object를 통해 template 정리  (0) 2020.07.31
[Node.js] 글 수정  (0) 2020.07.31
[Node.js] 글 생성  (0) 2020.07.31
[Node.js] Package Manger  (0) 2020.07.30

수정링크 생성 (홈페이지에서는 create만 보이고 각 페이지에서는 update가 보이도록 하기 )

temlpateHTML{ } 안에 <a href="/update">update</a> 추가

templateHTML 에서 control을 추가

<a href="/create">create</a> <a href="/update">update</a> 를 ${control}로 수정

function templateHTML(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>
  `;
}

 

모든 메뉴가 보이는 부분에 a 태그로 링크를 설정한다. 

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}`,
              `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
            );
            response.writeHead(200);
            response.end(template);
          });
        });
      }

 

수정할 정보 전송 ( update를 클릭했을 때 보여지는 화면 생성)

form 과 read 기능 필요

기존의 내용을 가져올 수 있도록 fs.readFile()을 통해 데이터를 가져오고 이 데이터를 input의 value 로 표시되게끔 입력

id 기존 값, title 바뀐값

hidden 속성 : 사용자에게 정보가 보이지 않기 때문에 데이터를 보낼 때 유용하게 사용 

 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 = templateList(filelist);
          var template = templateHTML(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(template);
        });
      });
    } 

 

수정된 내용 저장

수정된 데이터를 각 페이지의 파일에 저장할 때, 기존의 id 값을 바뀐 title 값으로 수정하기 위해 fs.rename( ) 사용

"node.js file rename" - 검색 결과 아래 사진 참고 

fs.rename(이전 경로,새로운 경로,callback 함수){ } 안에 fs.writeFile(새로운 경로, 페이지 내용, encoding, callback함수)로 파일을 수정하고 저장

 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();
            })
          });
      });
    } 

'Web > Node.js' 카테고리의 다른 글

[Node.js] object를 통해 template 정리  (0) 2020.07.31
[Node.js] 글 삭제  (0) 2020.07.31
[Node.js] 글 생성  (0) 2020.07.31
[Node.js] Package Manger  (0) 2020.07.30
[Node.js] synchronous(동기적) asynchronous(비동기적)  (0) 2020.07.27

UI 만들기

기존에 있던 if(pathname === '/') 이외에 /가 아닌 create일 때의 조건문 생성

해당 조건문 내용 : 글을 작성할 수 있는 페이지 작성 , 기존의 template에 html의 form 태그 추가 

else if(pathname === '/create'){
      fs.readdir('./data', function(error, filelist){
        var title = 'WEB - create';
        var list = templateList(filelist);
        var template = templateHTML(title, list, `
          <form action="http://localhost:3000/process_create" 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(template);
      });

 

Post 방식으로 전송된 데이터 받기 

 

"node.js post data" 검색 후 나온 결과 - 아래 사진 참고 

웹브라우저가 post방식으로 데이터를 전송할 데이터가 엄청나게 많으면 컴퓨터에 무리가 가는 문제가 생김 -> node.js는 post방식으로 전송되는 데이터가 많을 경우를 대비해서 특정한 양의 데이터를 서버에서 수신할 때마다 서버는 callback 함수를 호출하도록 약속되어있음 

form의 post 방식으로 가져온 데이터를 /create_process 페이지로 넘어가면서 확인하고자 할 때, createServer의 인자인 request로 데이터를 요청하고, 받은 데이터를 query string 모듈의 parse로 객체화 하여 데이터를 콘솔에 출력할 수 있음

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
      });
      response.writeHead(200);
      response.end('success');
    } else {
      response.writeHead(404);
      response.end('Not found');
    }
 

 

파일 생성

post 방식으로 전송된 데이터를 data directory안에 file의 형태로 저장하는 방법

"node.js file write"

https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_fs_writefile_file_data_options_callback

 

File system | Node.js v12.18.3 Documentation

 

nodejs.org

위에서 작성한 request.on('end',function(){ } 안에 다음의 코드를 작성한다. 

fs.writeFile(`data/${title}`, description, 'utf8', function(err){
            response.writeHead(200);
            response.end('success');
          })

 

리다이렉션

콜백함수 안에서 작성한 페이지를 확인하기 위해 그 페이지로 넘어가는 것

"node.js redirection"  - 검색 후 나온 결과 아래 사진 참고

위에서 작성한 fs.writeFile(){ } 안의 response.writeHead( ) 부분을 아래와 같이 수정

fs.writeFile(`data/${title}`, description, 'utf8', function(err){
            response.writeHead(302, {Location: `/?id=${title}`});
            response.end();
          })

Package Manger : 소프트웨어들을 생성, 설치, 업데이트, 삭제, 등을 관리해 주는 프로그램 

 

NPM : Node.js 에서 가장 광범위하게 사용, 기본적으로 node.js를 설치할 때 함께 설치되는 package manger

 

https://pm2.keymetrics.io/

 

PM2 - Home

Advanced process manager for production Node.js applications. Load balancer, logs facility, startup script, micro service management, at a glance.

pm2.keymetrics.io

pm2 : node.js를 하나하나 껐다 켰다를 반복할 필요 없이 변화가 생기면 자동으로 껐다 켜주는 역할

 

npm install pm2 -g

-g의 의미 : 내가 깔고 있는 소프트웨어가 독립된 존재로 컴퓨터 내에서 쓰일 수 있도록 한다. 

 

pm2 start 실행시키고자하는파일이름.js

파일 실행 

 

pm2 start 실행시키고자하는파일이름.js --watch

이전의 경우 코드를 수정하면, 실행한 파일을 종료(ctrl+c) 후 다시 실행시켜야 하는데, 이제는 reload만 하면 바로 실행됨

 

pm2 log

pm2 start main.js --watch 를 사용하면 실행이 됐는데 백그라운드로 몰래 실행되고 있기 때문에 어떤 상태인지 알 수 없음 그래서 pm2 log를 사용함

pm2 log는 어떠한 문제점이 있을 때 그 문제점을 바로 보여줌

 

pm2 list

실행되는 프로세스의 리스트

 

pm2 start 실행시키고자하는파일이름.js --watch --no-daemon

daemon : 백그라운드로 실행되는 프로그램

no-daemon : daemon이 아닌상태로 실행 

pm2를 실행하는 것과 동시에 log까지 볼 수 있음 

[ctrl+c] 입력시 종료 (안되는 때도 있음)

 

pm2 monit

pm2에 의해 현재 실행되고 있는 프로그램들이 보임

 

pm2 stop 실행종료하고자하는프로세스의이름

실행종료

 

pm2 kill

pm2로 켜진 프로세스들을 전부 종료

synchronous (동기적)

우리가 일을 할 때를 생각해보자

일 10분 -> 일 2시간 -> 일 1시간 -> 일 40분

일이 다 끝날때까지 기다리다가 다 끝나면 다른 일 시작

(일이 오랫동안 처리되어야 하는 경우에도 기다렸다가 다음 일 처리)

 

asynchronous (비동기적) - 효율적 but 복잡

일 10분 -> 일 2시간

               -> 일 1시간 

일이 끝날때까지 기다리지 않고 다음 일 진행

(병렬적으로 동시에 여러가지 일 처리)

 

동기 & 비동기 가 코드 level 에서 어떤 차이를 갖는지 ?

https://nodejs.org/dist/latest-v12.x/docs/api/https://nodejs.org/dist/latest-v12.x/docs/api/fs.html

 

Index | Node.js v12.18.3 Documentation

 

nodejs.org

위의 링크에 들어가서 확인해 보면 

이름 뒤에 sync가 붙는 경우가 있고 아닌 경우가 있다. 

 

readFileSync (동기적)

fs.readFileSync(path[, options]);

// syntax directory 안에 sample.txt가 저장되어있음
// sample.txt 내용은 'B'
console.log('A');
var result = fs.readFileSync('syntax/sample.txt','utf8');
console.log(result);
console.log('C');

A B C 순서로 출력됨

 

readFile (비동기적)

fs.readFile(path[,options],callback);

readFileSync는 return 값을 반환하는데,

반면에 readFile은 return값을 주지 않기 때문에 함수를 세번째 인자로 주어야 

함수의 첫번째 parameter : error가 있다면 'err' 인자로 제공

두번째 parameter : 파일의 내용을 인자로서 구분해주도록 약속되어있음

// syntax directory 안에 sample.txt가 저장되어있음
// sample.txt 내용은 'B'
console.log('A');
fs.readFile('syntax/sample.txt','utf8',function(err,result){
    console.log(result);
});
console.log('C');

A C B 순서로 출력됨

readFile이 동작이 완료되기 전에 'C 출력'이 실행됨

 

callback

var a = function(){
    console.log('A');
}

위 코드를 보면 "a라는 변수에 값으로써 함수를 정의  : javascript에서는 함수 = 값" 이라는 점을 알 수 있다. 

 

var a = function(){
    console.log('A');
}

function showfunc(callback){
    callback();
}

showfunc(a);

-위 코드 해설-

showfunc라는 오랜시간이 걸려 동작하는 함수가 실행되고

callback 이라는 parameter는 a가 가리키는 함수를 가리키게 된다

callback()이라는 함수를 호출하면 a가 가리키는 함수가 실행된다

 

완전히 똑같은 코드는 개선의 여지가 있음 - " 중복 제거"

 

<기존 코드>

var http = require('http');
var fs = require('fs');
var url = require('url');
 
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 = '<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);
        })
 
 
 
      } else {
        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>';
          fs.readFile(`data/${queryData.id}`, 'utf8', function(err, description){
            var title = queryData.id;
            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);
          });
        });
      }
    } else {
      response.writeHead(404);
      response.end('Not found');
    }
 
 
 
});
app.listen(3000);

 

1. 중복된 부분 (1)

 `
          <!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>
          `;

 

2. 함수화 -> 함수 templateHTML

 

3. 정리

 

해당 부분 안에 

<h2>${title}</h2>
<p>${description}</p>

부분을 ${body}로 바꾼다. ( 페이지 형태에 따라 형식이 다를 수 있는 부분이기 때문에 변경)

 

function templateHTML(title,list,body) 정의

호출부분은 var template = templateHTML(titlelist`<h2>${title}</h2>${description}`); 로 바꾼다. 

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>
  `;
}

 

4. 중복된 부분이 또 없는지 check

 

5. 중복된 부분 (2) 

          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>';

 

6. 함수화 -> templateList()

 

7. 정리

list 라고 하는 값 return 

코드를 실행하기 위해서는 filelist라는 값이 필요한데, 함수의 매개변수로 filelist를 입력받아야 함

-> function templateList(filelist){ }

호출 부분 : var list = templateList(filelist); 

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 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);

+ Recent posts