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] 15. 제작-글 수정 본문

대딩코딩/웹개발 스터디

[Node.js] 15. 제작-글 수정

시데브 2023. 11. 19. 17:11
해당 게시물은 유튜브 생활코딩 "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>`
            );  //home에서는 update 빼고 create만
            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>`  
              );  //id값을 선택한 페이지에서는 update ui가 나오도록
              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 = "http://localhost:3000/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 <- var app = http.createServer(function(request,response)
      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 {
      response.writeHead(404);
      response.end('Not found')
    }
});
app.listen(3000);

>>templateHTML의 list와 body 사이를 control로 대체하고 create 옆에 update ui 생성

 

    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>`
            );  //home에서는 update 빼고 create만
            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>`  
              );  //id값을 선택한 페이지에서는 update ui가 나오도록

>> home에서는 create만, 링크를 들어가면 update가 나오게

 

css에서 update 누르면 위와 같이 id가 CSS인 주소로 이동

 

제작-글 수정-수정할 정보 전송

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>`  
              ); 
              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);
          //value 태그로 기본값을 title로
          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 {
      response.writeHead(404);
      response.end('Not found')
    }
});
app.listen(3000);
<input type = "hidden" name="id" value = "${title}">

 

 

>> id는 유지, title은 입력한 정보인 CSS3

 

제작-글 수정-파일명 변경, 내용 저장

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>`  
              ); 
              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 {
      response.writeHead(404);
      response.end('Not found')
    }
});
app.listen(3000);
    } 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();
          })
        });

>>id의 이름을 가진 파일명을 title로 변경

 

CSS3 입력 시에 기존 CSS이던 파일명이 변경되고 그대로 웹 페이지에도 적용