처음부터 차근차근

Node.js 파일 리스트 읽어오기 본문

FrameWork/Node.js

Node.js 파일 리스트 읽어오기

HangJu_95 2023. 5. 30. 14:17
728x90

파일 리스트 읽어오기

먼저 Nodejs file list in directory를 검색해서 파일 리스트를 읽어오는 방법을 검색해보자.

굉장히 친절하게 알려준다.

https://stackoverflow.com/questions/2727167/how-do-you-get-a-list-of-the-names-of-all-files-present-in-a-directory-in-node-j

 

How do you get a list of the names of all files present in a directory in Node.js?

I'm trying to get a list of the names of all the files present in a directory using Node.js. I want output that is an array of filenames. How can I do this?

stackoverflow.com

var testFolder = './data';
var fs = require('fs');
 
fs.readdir(testFolder, function(error, filelist){
  console.log(filelist);
})

fs.readdir 메소드를 통해 폴더의 위치를 지정해주면 filelist를 읽어오는걸 확인 할 수 있다.

 

이것을 Main.js에 적용하여, filelist가 변경되었을 경우, 동적으로 알아서 불러올 수 있도록 표현하고, list를 출력해보자.

 

var http = require('http');
var fs = require('fs');
var url = require('url');
 
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 = '<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>';
          var template = `
          <!doctype html>
          <html>
          <head>
            <title>WEB1 - ${title}</title>
            <meta charset="utf-8">
          </head>
          <body>
            <h1><a href="/">WEB</a></h1>
            ${list}
            <h2>${title}</h2>
            <p>${description}</p>
          </body>
          </html>
          `;
          response.writeHead(200);
          response.end(template);
        })
      } else {
        fs.readdir('./data', function(error, filelist){
          var title = 'Welcome';
          var description = 'Hello, Node.js';
          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>';
          fs.readFile(`data/${queryData.id}`, 'utf8', function(err, description){
            var title = queryData.id;
            var template = `
            <!doctype html>
            <html>
            <head>
              <title>WEB1 - ${title}</title>
              <meta charset="utf-8">
            </head>
            <body>
              <h1><a href="/">WEB</a></h1>
              ${list}
              <h2>${title}</h2>
              <p>${description}</p>
            </body>
            </html>
            `;
            response.writeHead(200);
            response.end(template);
          });
        });
      }
    } else {
      response.writeHead(404);
      response.end('Not found');
    }
});
app.listen(3000);

if문 바로 앞에 fs.readdir 메소드를 추가시켰으며, 중간에 while 반복문을 넣어주어, list를 표현하였다.

        fs.readdir('./data', function(error, filelist){
          var title = 'Welcome';
          var description = 'Hello, Node.js';
          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>';

 

 

 

'FrameWork > Node.js' 카테고리의 다른 글

Node.js Synchronous & Asynchronous  (0) 2023.05.30
Node.js 함수를 이용해서 main.js 정리정돈하기  (0) 2023.05.30
Node.js 홈페이지 구현  (0) 2023.05.30
Node.js Not found 구현  (0) 2023.05.30
Node.js 파일 읽기 구현  (0) 2023.05.30