nodejs의 fs.readdir을 mysql로 변경 -읽기

piper ·2024년 4월 16일
0

Nodejs

목록 보기
6/9

앞에서 만들었던 fs.readdir은 비동기적으로 디렉토리의 파일 및 하위 디렉토리 목록을
읽을 수 있는 함수이다. 이 부분을 mysql에 저장되어 있는
데이터를 읽어 올 수 있는 부분을 만들 것이다.

먼저 작성되어 있는 main.js에 모듈을 불러온다.

var mysql = require("mysql");
var db = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "비밀번호",
  database: "데이터베이스이름",
});
db.connect();

그 뒤에 파일 목록을 읽어드리는 함수를 아래와 같이 교체해준다.
콘솔에 토픽을 찍어보면 mysql 데이터베이스에 담겨있는
데이터들이 배열안의 객체로 들어있는 것을 볼수있다.
때문에 이 앱의 모듈 함수로 쓰고 있는 template.js 파일의
ui를 그리고 있는 이 부분에 가서

//topics[i].id 그리고 
topics[i].title로 바꿔준다. 
`<li><a href="/?id=${topics[i].id}">${topics[i].title}</a></li>`;

이렇게 하면 쿼리가 id에 따라서 출력되고 제목도 출력이 된다.

db.query(`SELECT * FROM topic`, function (err, topics) {
        var title = "Welcome 환영합니다.";
        var description = "Hello, Node.js";
        var list = template.list(topics);
        var html = template.HTML(
          title,
          list,
          `<h2>${title}</h2>${description}`,
          `<a href="/create">create</a>`
        );
        console.log(topics);
        response.writeHead(200);
        response.end(html);
      });

이제 다음에 할 것은 루트 페이지가 아닌 내용이 있을때 else 안의 함수 또한 바꾸어주어야 한다.
data 폴더에서 내용을 읽어주었을 때는 data가 파싱되었었는데 이제는 id 값이 1인지 2인지 3인지에 따라서 해당 테이블에 있는 데이터들을 각기 출력해주어야한다.
그 부분을 매개변수로 표현하는 부분을 아래와 같이 표기할수있다.

`SELECT * FROM topic where id = ${queryData.id}`

이후 콘솔에 topic을 찍어보면 아래와 같이 객체가 출력된다.
필요한 부분이 화면에 나오도록 프린트하면 된다. 배열의 길이가 한개니까

topic[0].title 이런식으로 출력할 수 있다. 
[
0|main   |   RowDataPacket {
0|main   |     id: 3,
0|main   |     title: 'SQL Server',
0|main   |     description: 'SQL Server is ...',
0|main   |     created: 2018-01-20T02:01:10.000Z,
0|main   |     author_id: 2
0|main   |   }
0|main   | ]

전체적으로 바꿔준 코드는 아래와 같다.

else {
      db.query(`SELECT * FROM topic`, function (err, topics) {
        db.query(
          `SELECT * FROM topic where id = ${queryData.id}`,
          function (err2, topic) {
            console.log(topic);
            var title = topic[0].title;
            var description = topic[0].description;
            var list = template.list(topics);
            var html = template.HTML(
              title,
              list,
              `<h2>${title}</h2>${description}`,
              `<a href="/create">create</a>`
            );
            response.writeHead(200);
            response.end(html);
          }
        );
      });
    }

하지만 여기서 주의해야할 것이있다. 사용자가 id를 입력할때 id가 중복되거나
사용하지 말아야하는 것을 사용할 수도 있다. 물음표를 써주어서 하는 방법으로 바꾸어주고
업데이트와 삭제의 id와 value에도 queryData.id로 교체해준다.

else {
      db.query(`SELECT * FROM topic`, function (err, topics) {
        db.query(
          `SELECT * FROM topic where id =?`,
          [queryData.id],
          function (err2, topic) {
            console.log(topic);
            var title = topic[0].title;
            var description = topic[0].description;
            var list = template.list(topics);
            var html = template.HTML(
              title,
              list,
              `<h2>${title}</h2>${description}`,
              `
              <a href="/create">create</a>
            <a href="/update?id=${queryData.id}>update</a>
            <form action="delete_process" method="post">
              <input type="hidden" name="id" value="${queryData.id}">
              <input type="submit" value="delete">
            </form>`
            );
            response.writeHead(200);
            response.end(html);
          }
        );
      });
profile
연습일지

0개의 댓글