본문 바로가기

NodeJS

Node.js 폴더에 파일 존재 유무 확인하기

node.js readdir

Node.js에서 반드시 모듈 fs를 require를 해야합니다.

const fs = require('fs');

 

폴더 구조 : 

폴더구조 : publick안에 있는 type폴더

의도 : 

type폴더 안의 A-1 ~ C-4 폴더안에 있는 png 파일의 유무를 알고싶었습니다. png 파일의 이름은 폴더의 이름과 같습니다. 

ex) /public/type/A-1/A-1.png 

const tDir = __dirname + '/../public/type/';

  fs.readdir(tDir, (err, data)=>{
    if(err) throw err;

    data.forEach((item, i) => {
      const imgFile = tDir+item;
      // console.log(imgFile+"/"+item+".png");

      fs.exists(imgFile+"/"+item+".png",  function(exists){
        if(exists){
          console.log("exixts! : ",exists);
        } else {
          console.log("No exixts! : ",exists);
        }
       });


      // fs.readdir(imgFile, (err, data)=>{
      //   if(err) throw err;
      // });// END readdir

    }); // END forEach
  }); // END readdir

설명 : 

readdir로 type 폴더안에 있는 폴더 이름을 ForEach로 읽어옵니다.

A-1 ~ C-4 폴더의 이름을 얻고나서, 다시 A-1 ~ C-4 각 폴더안에 있는 png 파일 의 존재 유무를 exists로 얻어옵니다.

 

에러 났던 곳 : 

const tDir = __dirname + '/../public/type/';

루트 폴더를 포함한 폴더 경로를 넣어줄때, '/../' 이 부분을 이렇게 써줘야 하는지 모르고 처음에는 단순하게 './public/~'이런 식으로 써줘서 에러가 계속 났었음..... 

 

728x90
300x250