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}
${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 template = {
HTML:function(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}
${body}
</body>
</html>
`; },
list:function(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;
}
}
위 template를 사용하는 부분 수정
templateList을 template.list로 변경
templateHTML을 template.HTML으로 변경하고 template라고 되어있는 변수를 html로 수정
예시( 주석: 기존코드)
/* var list = templateList(filelist);
var template = templateHTML(title, list,
`<h2>${title}</h2>${description}`,
`<a href="/create">create</a>`
);
response.writeHead(200);
response.end(template);
*/
var list = template.list(filelist);
var html = template.HTML(title, list,
`<h2>${title}</h2>${description}`,
`<a href="/create">create</a>`
);
response.writeHead(200);
response.end(html);
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>
<a href="/delete?id=${title}">delete</a>`
);
response.writeHead(200);
response.end(template);
});
});
}
}
글을 삭제 할 때, 따로 보여줄 페이지가 없기 때문에 링크는 필요하지 않음
따라서 form 태그로 지울 id값을 가지고 delete_process로 넘어가야함
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);
});
});
}
}
글 삭제 기능 완성(삭제 요청 처리)
delete_process
"node.js delete file" - 검색 결과 중 아래 사진 참고
post 방식으로 받아온 id 값으로 지우고자 하는 경로를 fs.unlink()에 넣고 그 다음으로 넘어갈 페이지를 정해줌
fs.unlink( ){ } 안에 response.writeHead(302,넘어갈 페이지) 입력
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(error){
response.writeHead(302, {Location: `/`});
response.end();
})
});
}
<전체 코드>
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>WEB1 - ${title}</title>
<meta charset="utf-8">
</head>
<body>
<h1><a href="/">WEB</a></h1>
${list}
${control}
${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}`,
`<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 = 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">${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 = 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(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 = 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);
수정된 데이터를 각 페이지의 파일에 저장할 때, 기존의 id 값을 바뀐 title 값으로 수정하기 위해 fs.rename( ) 사용
"node.js file rename" - 검색 결과 아래 사진 참고
fs.rename(이전 경로,새로운 경로,callback 함수){ } 안에 fs.writeFile(새로운 경로, 페이지 내용, encoding, callback함수)로 파일을 수정하고 저장
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(error){
fs.writeFile(`data/${title}`, description, 'utf8', function(err){
response.writeHead(302, {Location: `/?id=${title}`});
response.end();
})
});
});
}
기존에 있던 if(pathname === '/') 이외에 /가 아닌 create일 때의 조건문 생성
해당 조건문 내용 : 글을 작성할 수 있는 페이지 작성 , 기존의 template에 html의 form 태그 추가
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);
});
Post 방식으로 전송된 데이터 받기
"node.js post data" 검색 후 나온 결과 - 아래 사진 참고
웹브라우저가post방식으로데이터를전송할때, 데이터가엄청나게많으면컴퓨터에무리가가는문제가생김 -> node.js는post방식으로전송되는데이터가많을경우를대비해서 특정한 양의 데이터를 서버에서 수신할 때마다 서버는 callback 함수를 호출하도록 약속되어있음
form의 post 방식으로 가져온 데이터를 /create_process 페이지로 넘어가면서 확인하고자 할 때, createServer의 인자인 request로 데이터를 요청하고, 받은 데이터를 query string 모듈의 parse로 객체화 하여 데이터를 콘솔에 출력할 수 있음
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 {
response.writeHead(404);
response.end('Not found');
}
파일 생성
post 방식으로 전송된 데이터를 data directory안에 file의 형태로 저장하는 방법
// syntax directory 안에 sample.txt가 저장되어있음
// sample.txt 내용은 'B'
console.log('A');
var result = fs.readFileSync('syntax/sample.txt','utf8');
console.log(result);
console.log('C');
A B C 순서로 출력됨
readFile (비동기적)
fs.readFile(path[,options],callback);
readFileSync는return값을반환하는데,
반면에readFile은return값을주지않기때문에함수를세번째인자로주어야함
함수의첫번째parameter : error가있다면'err'를인자로제공
두번째parameter : 파일의내용을인자로서구분해주도록약속되어있음
// syntax directory 안에 sample.txt가 저장되어있음
// sample.txt 내용은 'B'
console.log('A');
fs.readFile('syntax/sample.txt','utf8',function(err,result){
console.log(result);
});
console.log('C');
A C B 순서로 출력됨
readFile이 동작이 완료되기 전에 'C 출력'이 실행됨
callback
var a = function(){
console.log('A');
}
위 코드를 보면 "a라는 변수에 값으로써 함수를 정의 : javascript에서는 함수 = 값" 이라는 점을 알 수 있다.
var a = function(){
console.log('A');
}
function showfunc(callback){
callback();
}
showfunc(a);
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>';
6. 함수화 -> templateList()
7. 정리
list 라고 하는 값 return
코드를 실행하기 위해서는 filelist라는 값이 필요한데, 함수의 매개변수로 filelist를 입력받아야 함
-> function templateList(filelist){ }
호출 부분 : var list = templateList(filelist);
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 http = require('http');
var fs = require('fs');
var url = require('url');
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}
${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 {
response.writeHead(404);
response.end('Not found');
}
});
app.listen(3000);