이전 포스팅에서는 파일 생성까지만 했었는데 오늘은 파일을 수정하고 삭제하는 것을 해보겠습니다.
UI에 수정, 삭제 추가
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>
`;
}
Home화면에서는 create만 할 수 있게 하고, 나머지 화면에서는 create, update, delete를 할 수 있게 하기 위해서 이 내용이 들어갈 부분은 control로 바꿔줍니다.
if(pathname === '/'){
if(queryData.id === undefined){ //Home화면
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 === '/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);
});
});
}
파일을 수정하는 링크를 "/update" 라고 주었으므로 pathname === '/update' 일 때를 정의해줍니다. 파일을 삭제할 때와 같이 만들어주고, 파일을 수정할 때 원래 어떤 데이터가 있는지 확인할 수 있도록 value="${title}" 와 ${description}을 넣어줍니다. 타이틀을 수정할 경우 원래 타이틀 값을 가지고 있어야 파일을 찾을 수 있으므로 <input type="hidden" name="id" value="${title}"> 을 넣어줍니다. 사용자가 수정하면 안되므로 hidden으로 보이지 않게 합니다.
else if(pathname === '/update_process'){
var body = '';
request.on('data', function(data){ //데이터를 수신할 때마다 data콜백 수행
body = body + data;
});
request.on('end', function(){ // 더 이상 불러올 데이터가 없으면 end콜백 수행
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();
})
});
});
데이터를 받아온 후 rename( )을 사용하여 파일 이름을 바꾸어 줍니다. 첫번째 인자는 원래 타이틀 위치, 두번째 인자는 새로운 파일 위치입니다. 그 다음 writeFile( )을 사용하여 파일의 정보를 수정해줍니다. 수정 후 리다이렉션을 해줍니다.
파일 삭제
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();
})
});
}
파일을 삭제하는 링크를 "/delete_process" 라고 주었으므로 pathname === '/delete_process 일 때를 정의해줍니다. 파일 삭제는 unlink( )를 사용해서 해줍니다. `data/${id}` 는 파일 위치이고, 파일 삭제 후 Home화면으로 리다이렉션을 해줍니다.
실행 화면입니다.
전체 코드입니다.
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);
'Back-end > Node.js' 카테고리의 다른 글
[Node.js] 입력 정보와 출력 정보에 대한 보안 (0) | 2020.12.25 |
---|---|
[Node.js] 객체(Object), 모듈(Module) 사용하여 리팩토링 (0) | 2020.12.25 |
[Node.js] POST방식으로 데이터 전송하고 받기, 파일 생성, 리다이렉션 (0) | 2020.12.23 |
[Node.js] 동기와 비동기 / callback (0) | 2020.12.22 |
[Node.js] URL모듈을 통해서 동적 웹페이지 만들기 (0) | 2020.12.21 |