Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get all subdirectories and return their paths?

Assume there is the following folder structure:

/apps
|- /group1
|  |- /project1
|  |- /project2
|- /group2
|  |- /project3
|  |- /project4

I need to get the path of all projects – which are all two level deep (group folder and then project folder).

So I started with this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import { readdirSync } from 'fs'

const directoriesInDirectory = readdirSync([rootPath, 'apps'].join('/'), {
  withFileTypes: true
})
.filter((item) => item.isDirectory())
.map((item) => item.name)

This gives me all groups ['group1', 'group2'].

But I need to get this:

[
    'apps/group1/project1',
    'apps/group1/project2',
    'apps/group2/project3',
    'apps/group2/project4'
]

>Solution :

You need to perform readdirSync multiple times, once for the app directory, and the rest for the nested directories. Also, instead of using sync, if you adapt the non-blocking nature, you can use promises instead:

import { readdir } from 'fs/promises'

const startPath = [rootPath, 'apps'].join('/')

const parentDirs = (
  await readdir(startPath, {
    withFileTypes: true,
  })
)
  .filter((item) => item.isDirectory())
  .map((item) => item.name)

const projectPaths = (
  await Promise.all(
    parentDirs.map(async (dir) => {
      const projects = (
        await readdir(startPath + '/' + dir, {
          withFileTypes: true,
        })
      )
        .filter((item) => item.isDirectory())
        .map((item) => item.name)
      return { dir, projects }
    })
  )
)
  .map(({ dir, projects }) =>
    projects.map((project) => [startPath, dir, projects].join('/'))
  )
  .flat()

console.log(projectPaths) // ['apps/group1/project1', 'apps/group1/project2', ...]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading