[node.js] CRUD : update 기능 만들기
fs.rename('/tmp/hello', '/tmp/world', (err) => {
if (err) throw err;
console.log('renamed complete');
});
fs.stat('/tmp/world', (err, stats) => {
if (err) throw err;
console.log(`stats: ${JSON.stringify(stats)}`);
});
if (pathname === '/update'){
fs.readdir('./data',function( error, filelist){
fs.readFile(`data/${queryData.id}`,'utf8',function(err,description){
console.log(description);
var tatle = queryData.id;
var templat = makeInfo('Web - update',filelist,`
<form action="/update_process" method="post">
<p><input type="hidden" name ="id" value ="${tatle}"></p>
<p><input type="text" name ="tatle" placeholder="tatle" value ="${tatle}"></p>
<p><textarea name="description" rows="8" cols="80" name ="description"
placeholder="description"> ${description}</textarea></p>
<p><input type="submit"></p>
</form>
`,`<a href="/create">create</a> <a href="/update?id=${tatle}">update</a>`);
response.writeHead(200);
response.end(templat);
});
});
}else if (pathname === '/update_process'){
var body = '';
// requst data를 통해서 데이터가 들어와 body에 저장
request.on('data',function(data){
body += data;
});
// 그 후 end`로 넘어와 post에 담아서 뽑아 쓸수 있다
request.on('end',function(){
// post에 body데이터가 저장됨
var post = qs.parse(body);
var tatle = post.tatle;
var id = post.id;
var description = post.description;
fs.rename(`data/${id}`,`data/${tatle}`,(err) =>{
fs.writeFile(`data/${tatle}`,description,'utf8' err => {
// 302 요청은 페이지를 다른 곳으로 리다이렉션 시키는 것
response.writeHead(302,{Location:`/?id=${tatle}`});
response.end();
})
});
});
}