0

I have some Node JS javascript code that reads folders inside of a directory, however it's currently reading folders and files, and I just need it to read folders and can't figure out what U'm missing:

router.get('/check', (req, res) => {

  fs.readdir('./directory', function(err, files) {
    if (err) {
      res.status(500).send({ error: { status: 500, message: 'error' } })
      return
    }

    console.log('success')
  })

})

I was thinking about doing something like files[0].length > X for instance to only show names that contain more than X characters, or filter out file extensions etc, I ideally just need directories since I have a .empty file inside.

Ryan H
  • 2,620
  • 4
  • 37
  • 109

1 Answers1

0

You can check reference on documentation. readdir() will return contents of the directory. You need to filter folders or files. Simply you can call and create new array files.filter(fileName => fs.statSync(path + fileName).isFile().

ref

Update

Given sample code will filter files and folders into to seperated variables. You can implement into your project.

    const fs = require('fs');
    const path = require('path');
    
    const dir = fs.readdirSync(__dirname);
    const folders = dir.filter(element => fs.statSync(path.join(__dirname, element)).isDirectory());

    const files = dir.filter(element => fs.statSync(path.join(__dirname, element)).isFile);
    console.log('folders', folders, 'files', files);
Eren Yatkin
  • 186
  • 2
  • 9
  • This doesn't seem to work, I've added: `const folders = files.map(fileName => fs.statSync(path + fileName).isFile())`, and I have a folder called `test`, getting: `no such file or directory, stat '[object Object]test'` lol – Ryan H Jul 17 '20 at 13:32
  • @RyanHolton I editted my answer and added a sample code – Eren Yatkin Jul 18 '20 at 17:09