Search code examples
node.jsreaddir

NodeJS/fs.readdir - Ignore certain subdirectories when scanning for a specific set of subdirectories (closed)


Say we have a working directory containing subdirectories like so:

<workDir>
|— UselessFolder
|— NotThisFolder
|— SkipThisFolder
|— UsefulFolder
|— UsefulFolder2
|— UsefulFolder3

Is there a way that I can ignore the UselessFolder, NotThisFolder & SkipThisFolder subdirectories while scanning the working directory with fs.readdir?

The goal of the function that requires this, is to find the very last instance of the UsefulFolder subdirectories and do work with them later on. The function works fine most of the time, but it breaks in some cases due to the subfolders that I want to ignore that were stated above, I know this because if I completely remove the subfolders I want my function to ignore, the function will work fine, but in my case I can't delete any of the subdirectories within the working directory, so the only option is to ignore the ones I don't care about.

The code I'm currently using in my function to read the working directory and list its subdirectories is the following:

var workDir = '/home/user/workDir';

fs.readdir(workDir, { withFileTypes: true }, (error, files) => {
    if (error) {
        console.log('An error occured while reading the working directory! \n\n')
        console.log('Reason: ' + error);
        return;

    } else {
        var folderList = files
            .filter((item) => item.isDirectory())
            .map((item) => item.name);

        console.log(folderList);
    };

});

Solution

  • I'm not aware of a way to ask readdir itself to give you a filtered list. You will need to filter them yourself, something like this:

    let unwantedDirs = ['foo', 'bar'];
    var folderList = files
      .filter((item) => 
        item.isDirectory() && 
        !(unwantedDirs.includes(item.name)))