Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs readdir - only find files

When reading a directory, I currently have this:

  fs.readdir(tests, (err, items) => {

      if(err){
        return cb(err);
      }

      const cmd = items.filter(v => fs.lstatSync(tests + '/' + v).isFile());

      k.stdin.end(`${cmd}`);
  });

first of all I need a try/catch in there around fs.lstatSync, which I don't want to add. But is there a way to use fs.readdir to only find files?

Something like:

fs.readdir(tests, {type:'f'}, (err, items) => {});

does anyone know how?

like image 700
Alexander Mills Avatar asked Jul 23 '26 09:07

Alexander Mills


1 Answers

Starting from node v10.10.0, you can add withFileTypes as options parameter to get fs.Dirent instead of string.

// or readdir to get a promise
const subPaths = fs.readdirSync(YOUR_BASE_PATH, { 
  withFileTypes: true
});
// subPaths is fs.Dirent[] type
const directories = subPaths.filter((dirent) => dirent.isFile());
// directories is string[] type

more info is located at node documentation:

  • fs.Dirent
  • fs.readdirSync
  • fs.readdir
like image 119
buriedalive Avatar answered Jul 25 '26 01:07

buriedalive



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!