자바스크립트에서 함수의 사용
Node.js에서 동기와 비동기
- Synchronous : 순차적으로 일을 진행
- ASynchronous : 다중적으로 일을 진행
readFileSync를 사용한 txt파일 내의 값 출력
var fs = require('fs');
//readFileSync
console.log('A');
var result = fs.readFileSync('syntax/sample.txt', 'utf8');
console.log(result);
console.log('C');
readFile을 이용해 function 안에 있는 문서를 실행하고, 이는 다른 작업이 모두 끝난 다음에 처리된다.
콜백이란? : 프로그램이 끝난 후 실행되는 형태.
function a(){
console.log('A');
}
var a = function (){ //익명 함수
console.log('A');
}
// JavaScript에서는 함수 자체가 value가 될 수 있다.
function showfunc(callback){
callback();
}
showfunc(a);
출력값 : A
> npm install pm2 -g
이 명령어로 PM2를 설치해보자
따로 node를 껐다 킬 필요 없이 페이지가 리로드된다.
POST 방식으로 전송된 데이터 받기
request.on('data', function(data){
body = body + data; // CallBack이 실행될 때마다 데이터를 추가
});
web browser가 post방식으로 데이터를 전송할 때, 이 데이터의 크기가 클 때 콜백을 사용해 특정한 양의 데이터가 조각조각의 양을 수신할 때마다 서버는 이 콜백함수를 호출하도록 약속되어 있다. 이때 데이터의 인자(data)를 통해서 수신해주기를 약속
var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');
// HTML 중복 제거
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}
<a href = "/create">create</a>
${body}
</body>
</html>`;
}
function templateList(filelist){
var list = `<ul>`;
var i = 0;
while(i < filelist.length){ // filelist의 크기만큼 while문을 반복하며
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==='/') // path가 없는 코드로 접속
{
//home으로 갔을 때
if(queryData.id === undefined){
fs.readdir('./data', function(error, filelist){
//filelist는 data디렉터리 안의 피일 이름들
// console.log(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{ // id값이 있는 경우의 코드
fs.readdir('./data', function(error, filelist){
var list = templateList(filelist);
fs.readFile(`data/${queryData.id}`, 'utf8',function(err, description){
var title = queryData.id;
// var description = data;
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 = "title"></p>
<p> <textarea name = "description" placeholder = "description"></textarea>
</p>
<p>
<input type = "submit">
</p>
</form>
`);
response.writeHead(200);
response.end(template);
}) // readdir의 괄호에 해당하는 token을 찾아야함.
}
else if(pathname === '/create_process'){
var body = '';
request.on('data', function(data){
body = body + data; // CallBack이 실행될 때마다 데이터를 추가
});
request.on('end', function(){ // 더 이상 들어올 data가 없을 때
var post = qs.parse(body); // parse로 데이터를 객체화할 수 있다.
var title = post.title;
var description = post.description;
console.log(post.title);
})
response.writeHead(200);
response.end("success");
}
else { // path가 있는 곳으로 접속했을 때
response.writeHead(404); // 200이라는 숫자는 파일을 성공적으로 접속했음을 알리게 되고, 404는 에러가 떴음을 알림
response.end('Not found');
}
});
app.listen(3000);
데이터를 파일의 형태로 저장하는 방법!
https://hellominchan.tistory.com/11
[Node.js] PM2 소개와 설치 및 사용법
[Node.js] PM2 소개와 설치 및 사용법 (PM2 버전 : 4.2.1, 글쓴날 : 2020.02.11) * 글 쓴 날 기준으로 PM2의 최신 버전은 4.2.3입니다. 1. PM2란 무엇인가? 1) 프로세스 매니저 우리의 Node.js에 사용성을 200%..
hellominchan.tistory.com
수정하기 (이 부분 다시 복습!!)
1. 해당 게시글로 들어가서 update 버튼을 눌렀을 때 해당 update?id=CSS 페이지로 이동하게끔 하기
2. form 화면 구성하기 (readdir)
3. form에 수정하는 데이터를 넣기
hidden 태그를 사용하기
var member = ['egoing', 'k8805', 'joya'];
// 0, 1, 2 index
console.log(member[1]);
var i = 0;
while(i < member.length)
{
console.log('array loop', member[i]);
i = i + 1;
}
var roles = {
'programmer':' egoing',
'designer':'k8805',
'manager':'joya'
} // object
console.log(roles.designer); //k8805
for(var name in roles) { // name 변수에는 객체의 식별자(인덱스)
console.log('object => ', name, 'value =>', roles[name]);
}
member은 Array, roles는 object이다.
for문에서 roles의 인덱스에 대한 값을 출력한다.
<
https://www.npmjs.com/package/sanitize-html
sanitize-html
Clean up user-submitted HTML, preserving whitelisted elements and whitelisted attributes on a per-element basis
www.npmjs.com
<script> 태그에 대한 안정성을 확보
var filteredPath = path.parse(queryData.id).base;
fs.readFile(`data/${filteredPath}`, 'utf8',function(err, description){
var title = queryData.id;
// var description = data;
var sanitizedTitle = sanitizeHtml(title);
var sanitizedDescription = sanitizeHtml(description);
var list = template.list(filelist);
var html = template.html(title, list, `<h2>${sanitizedTitle}</h2>${sanitizedDescription}`,
`<a href = "/create">create</a>
<a href="/update?id=${sanitizedTitle}">update</a>
<form action = "delete_process" method="post">
<input type="hidden" name="id" value="${sanitizedTitle}">
<input type="submit" value = "delete">
</form>`
);
response.writeHead(200);
response.end(html);
});
});
'Framework > Node.js' 카테고리의 다른 글
인프런 노드 리액트 기초 강의 (Node JS, Express JS) 1~10강 (0) | 2021.07.30 |
---|---|
생활코딩 Node.js 1~24강 내용 정리 (0) | 2021.07.20 |