https://opentutorials.org/course/3332/21028
생활코딩님의 Node.js강의를 참고하였습니다.
1.update 링크 제작
<a href="/update?id=${title}">update</a>
2.update
else if(pathname === '/update'){
// './data' 디렉토리의 파일 목록을 읽어옴
fs.readdir('./data', function (error, filelist) {
// 'data/' 디렉토리의 queryData.id에 해당하는 파일을 읽어옴
fs.readFile(`data/${queryData.id}`, 'utf8', function (err, description) {
var title = queryData.id; // 파일 이름을 title로 설정
var list = templateList(filelist); // 파일 목록을 리스트 형식으로 변환
// HTML 템플릿 생성
var template = templateHTML(title, list,
`<h2>${title}</h2>${description}`, // 현재 제목과 설명을 보여줌
`
<form action="/update_process" method="post"> <!-- 폼 제출 시 /update_process로 POST 요청을 보냄 -->
<input type="hidden" name="id" value="${title}"> <!-- 현재 제목을 hidden input으로 전달 -->
<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>
`);
response.writeHead(200); // HTTP 200 OK 상태 코드 전송
response.end(template); // 클라이언트에게 HTML 템플릿을 전송하고 응답 종료
});
});
}
3.update 처리, redirection
else if(pathname=== "/update_process"){
var body = '';
// 데이터를 받을 때마다 data 이벤트가 발생, body 변수에 데이터를 누적
request.on('data', function (data) {
body = body + data;
});
// 데이터 수신이 완료되면 end 이벤트 발생
request.on('end', function () {
var post = qs.parse(body); // 수신된 데이터를 파싱하여 post 객체로 변환
var id = post.id; // 기존 파일의 id(이름)
var title = post.title; // 새롭게 업데이트된 제목
var description = post.description; // 새롭게 업데이트된 설명
// 기존 파일명을 새로운 제목으로 변경
fs.rename(`data/${id}`,`data/${title}`,function(err){
// 파일 이름이 변경되면 새로운 제목과 설명으로 파일을 씀
fs.writeFile(`data/${title}`, description, 'utf8', function(err){
// 업데이트 완료 후, 새로운 파일 제목을 가진 페이지로 리디렉션
response.writeHead(302, {location:`/?id=${title}`});
response.end();
});
});
});
}
반응형
'BackEnd > Node.js' 카테고리의 다른 글
[Node.js] 삭제 (0) | 2024.09.01 |
---|---|
[Node.js] 파일생성과 리다이렉션 (0) | 2024.08.22 |
[Node.js] HTML Form (0) | 2024.08.16 |