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:
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', ...]