Node.js

Daniel·2022년 8월 4일
0

Node.js

목록 보기
2/2
post-thumbnail

동기와 비동기 (synchronous , aynchronous)


동기 (Synchronous)

  • 작업을 순차적 으로 실행한다.
  • 직렬적, 비효율적이지만 코드가 비교적 쉬움
var fs = require('fs');

console.log('A');
fs.readFile('syntax/sample.txt', 'utf8', function(err, result){
    console.log(result);
});
console.log('C');

결과값 ABC

비동기 (Asynchronous)

  • 작업을 동시에 실행한다.
  • 병렬적, 효율적이나 코드가 어려움
var fs = require('fs');
 
console.log('A');
var result = fs.readFileSync('syntax/sample.txt', 'utf8');
console.log(result);
console.log('C');

결과값 ACB

  • Node.js에서는 동기, 비동기 모두 지원
  • 비동기를 지원하는 함수는 함수명 + Sync이다.

콜백 함수

  • 매개변수(parameter)가 반드시 함수인 함수이다.
  • 매개변수로 함수를 받는이유는 비동기 처리를 위해서이다.

PM2 (PackageManager)


  • PM2 : https://pm2.keymetrics.io

  • 실행되고 있는 프로그램을 관리해주는 Node.js 툴이다. 우리가 디버깅을 할 때 계속 node main.js + ctrl+c 를 입력했다. PM2는 이러한 부분을 보다 관리하기 쉽게 도와준다.

글생성 UI


  • create 링크 생성
function templateHTML(title, list, body){
	~~~
	  <a href="/create">create</a>
	~~~
}
  • create를 클릭 했을 때의 실행코드
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);
      });
  • form태그를 이용하여 post방식으로 데이터를 넘겼다.

POST방식으로 전송된 데이터를 받는 법


  • 요청할때 웹브라우저가 받아온 정보 : request
  • 응답할때 웹브라우저에게 보낼 정보 : response
var app = http.createServer(function(request,response){
  ~~~
// 쿼리 스트링 선언
var qs = require('querystring');

~~~
   
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 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();
          })
      });
    }
  • writeFile : 데이터를 받아 파일을 생성
  • response.writeHead(302, {Location: /?id=${title}});
    • 302 : 해당 Location으로 이동 (리다이렉션)

글 수정 링크 생성


  • create, update링크를 매개변수로 받게 함수 수정
								//매개변수 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 생성
    ${control}
    ${body}
  </body>
  </html>
  `;
}
~~~
        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}`,
            // control 매개변수 값 (create 링크만 있음)
            `<a href="/create">create</a>`
          );
          response.writeHead(200);
          response.end(template);
        });
      } else {
        fs.readdir('./data', function(error, filelist){
          fs.readFile(`data/${queryData.id}`, 'utf-8', function(err, description){
            var title = queryData.id;
            var list = templateList(filelist);
            var template = templateHTML(title, list, 
              `<h2>${title}</h2>${description}`,
      	      // control 매개변수 값 (create, update 링크 둘다 있음)
              `<a href="/create">create</a > 
			<a href="/update?id=${title}">update</a>`
            );
            response.writeHead(200);
            response.end(template);
          });
        });
  ~~~

글 수정, 수정할 정보 전송


      // update의 경로로 접속시 조건문
   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으로 설정하여 사용자에게 보이지 않게 한다. 
			  // value를 title로 만들어 초기 입력값을 기존 값으로 설정한다.
              <input type="hidden" name="id" value="${title}">
			  // 이 부분도 value를 title로 두어 기존에 저장되어 있던 값을 불러온다.
              <p><input type="text" name="title" placeholder="title" value="${title}"></p>
              <p>
				// textarea는 input과 다르게 value가 없다 그래서 태그 사이에 값을 입력해준다.
                <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>`
          );

수정 내용 저장


~~~
// url주소가 /update_process인 경우
    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(err) {
		  // 기존 코드 재활용
          fs.writeFile(`data/${title}`, description , `utf-8` , function (err) {
            response.writeHead(302, {Location : `/?id=${title}`});
            response.end('success');
          });
        })            
        console.log(post);
      });
    }

삭제 버튼 링크 구현


 fs.readdir('./data', function(error, filelist){
          fs.readFile(`data/${queryData.id}`, 'utf-8', 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>
			  // templateHTML함수에 delete 폼 추가
              <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에 접근하는 경우
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() {
		  // 파일 삭제 후 홈으로 이동
          response.writeHead(302, {Location : '/'});
          response.end();
        })
      });
    }
profile
폐쇄

0개의 댓글