node.jsreaddir

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?


Solution

  • Unfortunately, fs.readdir doesn't have an option to specify that you're only looking for files, not folders/directories (per docs). Filtering the results from fs.readdir to knock out the directories is your best bet.

    https://nodejs.org/dist/latest-v10.x/docs/api/fs.html#fs_fs_readdir_path_options_callback

    The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the filenames passed to the callback. If the encoding is set to 'buffer', the filenames returned will be passed as Buffer objects.