-
[생활코딩] Node.js 강의 5일차Node.js 2021. 6. 24. 00:17
Node.js - 동기와 비동기 그리고 콜백
강의 내용
1) synchronous 동기 & asynchronous 비동기
- 동기 - 순차적으로 일을 처리한다.
예) 과제A가 끝날때까지 10시간이 걸린다면, 다 끝날때까지 기다렸다가 다른 과제B로 넘어감 - 비동기 - 동시에 여러일을 처리한다. (= 병렬적으로 일을 처리한다.)
예) 과제 A가 끝날때까지 10시간이 걸린다면, 일이 다 끝나면 연락하라고 하고 , 다른 일을 해. - Node.js는 비동기적 처리가 원활함 . 비동기적은 효율적이지만 매우 복잡하기도 함.
동기 vs 비동기
Node.js - 패키지 매니저와 PM2
강의 내용
1) 패키지 매니저
타인의 모듈을 이용해서 소프트웨어를 만들게 되는데 사용하는 모듈이 많아지면 복잡한 문제가 생긴다. 이를 관리하는 도구가 패키지 매니저이다. 이번 강의에서는 npm 과 실행중인 Node.js 애플리케이션을 관리하는 프로세스 매니저 PM2의 사용법을 알아봤다.
PM2 설치npm install pm2 -g
PM2 작동시키기 (pm2 start 파일명 , pm2 start 파일명 --watch)
pm2 start main.js
PM2로 변경사항, 에러 확인하기
pm2 log
PM2 monit 현재 작동시키는게 main.js 하나뿐이라서...pm2 사이트에 있는 모니터링 사진도 좌측에 붙여넣었다.pm2 monit
pm2 monit PM2 종료시키기
pm2 stop main.js
그 밖의 기능과 명령어들은 아래 링크를 통해 알아보자.
https://pm2.keymetrics.io/docs/usage/quick-start/PM2 - Quick Start
Advanced process manager for production Node.js applications. Load balancer, logs facility, startup script, micro service management, at a glance.
pm2.keymetrics.io
+) 추가 : PM2와 nodemon은 뭐가 다른가?
- nodemon은 코드가 바뀔때마다 자동으로 재시작(restart) 해주는 개발용 모니터.
"Simple monitor script for use during development of a node.js app." - PM2는 재시작(restart) 뿐 아니라 실서버 deploy, 로그 모니터링 등도 해주는 프로세스 매니저.
"Production process manager for Node.JS applications with a built-in load balancer."
(로드밸런서란 서버에 개하지는 부하load를 분산balancing 해주는 장치 또는 기술임)
HTML - Form (GET , POST) & App - 글생성 UI 만들기, POST 방식으로 전송된 데이터 받기
- 강의 내용
강의 목표 : 사용자가 웹을 통해서 데이터를 생성하고 수정하고 삭제할 수 있도록 하자
1) html의 form으로 데이터 생성 기능을 만들어 사용자가 서버쪽으로 데이터를 전송할 수 있게 한다.
form action 이 잘 작동하지 않았음을 확인할 수 있다.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="text"></p> <p> <textarea name="description" placeholder="description"></textarea> </p> <p><input type="submit"></p> </form> `); response.writeHead(200); response.end(template); });
네트워크 확인 결과
2) POST 방식으로 전송된 데이터를 받을 수 있게 한다.
- GET : 사용자가 입력한 정보를 서버로 queryString의 형태로 데이터를 전송하는 방식
보낼 수 있는 데이터의 길이 제한이 있고 queryString으로 정보가 노출되기에 중요한 정보를 다루면 안된다.
해서 GET은 데이터를 요청할 때만 사용된다. - POST : 사용자가 입력한 정보를 생성하고, 업데이트 하기 위해 데이터를 보낼 때 사용되는 메서드다.
3) 비동기방식 - 콜백함수 : request.on('data',function(data){body = body +data });
여기서 request는 createServer callback함수의 인자 (var app = http.createServer(function(request,response){..}; )
callback함수의 인자는 2개로, request는 요청할 때 웹브라우저가 보낸 정보, response는 응답할 때 서버가 웹브라우저에 보낼 정보를 담은 것이다.
post의 데이터가 많은걸 대비해 함수를 수신할 때마다 서버는 콜백함수를 호출하기로 약속했고 호출할 때마다 data 인자를 통해 데이터(사용자가 입력한 정보)를 주기로 약속됐다는 것을 의미하는 함수이다.
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; console.log(post); }); response.writeHead(200); response.end('success'); }
코드의 결과는 아래와 같다.네트워크 확인 , console.log(post) 확인 - GET : 사용자가 입력한 정보를 서버로 queryString의 형태로 데이터를 전송하는 방식
- 강의 코드
var http = require('http'); var fs = require('fs'); var url = require('url'); var qs = require('querystring'); function templateHTML(title,list,body){ return ` <!doctype html> <html> <head> <title>WEB- ${title}</title> <meta charset="utf-8"> </head> <body> <h1><a href="/">WEB</a></h1> ${list} <a href ="/create">create</a> ${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 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="text"></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; console.log(post.title); }); response.writeHead(200); response.end('success'); }else { response.writeHead(404); response.end('Not found'); } }); app.listen(3000);
'Node.js' 카테고리의 다른 글
[생활코딩] Node.js 강의 7일차 (0) 2021.06.29 [생활코딩] Node.js 강의 6일차 (0) 2021.06.25 [생활코딩] Node.js 강의 4일차 (0) 2021.06.21 [생활코딩] Node.js 강의 3일차 (0) 2021.06.18 [생활코딩] Node.js 강의 2일차 (0) 2021.06.18 - 동기 - 순차적으로 일을 처리한다.