Search code examples
node.jsreaddir

How to read folders which only have specific subfolder named in node js?


I have the following directory structure. The main directory has folders (ex. main_A) and some of them have a subfolder named "foo" but the other doesn't.

main
        |__main_A/foo
        |__main_B/a
        |__main_C/b
        |__main_D/foo
        |__main_E/foo
        |__main_F/c

Currently, I am using fsPromise.readdir() to read the files. My question is simply how to read and dive into only folders including foo subfolder?

Eventually, I need to read all files in the foo folder.

async function readFooFolder() {
  try {
    const pathProd = 'C:\\main';
    const fileList = await fsPromise.readdir(pathProd);
    console.log(fileList);
  } catch (err) {
    console.error(err);
  }
}

Solution

  • You can attempt to read the "foo" subdir for each directory in fileList. If the subddir does not exist for that directory, then an error with code ENOENT will be thrown.

    const path = require('path');
    async function readFooFolder() {
      try {
        const pathProd = 'C:\\main';
        const fileList = await fsPromise.readdir(pathProd);
        for (const subDir of fileList) {
          const fooDir = path.join(pathProd, subDir, 'foo');
          try {
            const fooFiles = await fsPromise.readdir(fooDir);
            // do something with fooFiles...
          } catch (fooErr) {
            if (fooErr.code != 'ENOENT') {
              console.error(fooErr);
            }
          }
        }
      } catch (err) {
        console.error(err);
      }
    }