Notice
Recent Posts
Recent Comments
«   2024/12   »
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
Archives
Today
Total
관리 메뉴

SYDev

[Node.js] 16. 제작-글 삭제 본문

대딩코딩/웹개발 스터디

[Node.js] 16. 제작-글 삭제

시데브 2023. 11. 22. 17:00
해당 게시물은 유튜브 생활코딩 "Node.js" 강의 영상을 참고했습니다.
(https://www.youtube.com/watch?v=3RS_A87IAPA&list=PLuHgQVnccGMA9QQX5wqj6ThK7t2tsGxjm&index=1)

 

 

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>WEB - ${title}</title>
    <meta charset="utf-8">
  </head>
  <body>
    <h1><a href="/">WEB2</a></h1>  
    ${list}
    ${control}
    ${body}
  </body>
  </html>
  `;
}

function templateList(filelist) {
  var list = '<ol>';
  var i = 0;
  while(i < filelist.length) {
    list += `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
    i++;
  }
  list += '</ol>';

  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 += 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">value = "${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 += data;
      });
      request.on('end', function() {
        var post = qs.parse(body);
        var id = post.id;
        var title = post.title;
        var description = post.description;
        //기존 파일명 id를 새로 입력한 title로 변경
        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 += 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);

 

삭제 버튼 구현

                 <form action="delete_process" method="post">
                  <input type="hidden" name="id" value="${title}">
                  <input type="submit" value="delete">
                 </form>`

>> 컨텐츠가 있는 페이지를 구현한 코드의 template에 해당 코드를 추가하여 post 형태의 delete 버튼 구현

>> get 형식으로 구현하면 안 됨!!

>> 클릭 시에 /delete_process 경로로 이동 

 

삭제 기능 구현

    else if (pathname === '/delete_process') {
      var body = '';
      request.on('data', function(data) {
        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();
        })
      });
    }

 

JavaScript 삭제