less than 1 minute read

13_Node.js 파일 Delete

  • App 제작 - 글 삭제 - 삭제 버튼 구현
  1. 특정한 글을 선택하면 delete 버튼이 활성화 된다.

  2. 데이터 디렉토리에서 이름이 같은 파일이 삭제된다.

    • 컨텐츠를 선택했을 때 활성화되는 부분에 delete 링크를 표현하기
      • delete 버튼을 클릭하면 바로 삭제된다.

         <a href="/delete?id=${title}">delete</a>
         링크는 클릭하면 이동되기 때문에 링크로 만들면 안된다.
        

쿼리 스트링이 들어있는 get 방식으로 구현하면 링크를 타고 들어갈 수 있기에 위험이 따르기에,
Form으로 바꾼다

        //delete 버튼이 생성
        <form>
            <input type="hidden" name="id" value="${title}">
            <input type="submit" value="delete">
         </form>

delete 버튼을 클릭하면 delete_process로 전송해야한다.

<form action="delete_process" method="post">

반드시 POST 방식 으로 전송하기.

자바스크립트 onsubmit을 이용하여 데이터를 전송할 때 재확인 할 수 있다.

<form action="delete_process" method="post" onsubmit="">

App 제작 - 글삭제 기능 완성

사용자가 전송한 정보를 바탕으로 삭제 처리하기.

삭제는 delete_process path를 통해서 한다.
기존의 update_process의 코드를 복사.

nodejs delete file 구글링
fs.unlink(path, callback) 비동기적으로 파일을 remove 한다.

// Assuming that 'path/file.txt' is a regular file.
fs.unlink('path/file.txt', (err) => {
  if (err) throw err;
  console.log('path/file.txt was deleted');
});

fs.unlink(`../nodejs1/data/${id}`, function(error){
          response.writeHead(302, {Location: `/`});
          response.end();
})

삭제가 끝난 다음에는 사용자를 홈으로 보낸다.
리다이렉션의 코드 번호 302번과. 헤더 정보 Location은 id값이 없어야한다.

파일 삭제 완료.