2021-08-05 01:06:06 +02:00
|
|
|
import { Dirent, promises } from 'fs'
|
2019-02-24 22:08:35 +01:00
|
|
|
import { join } from 'path'
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Recursively read directory
|
|
|
|
* @param {string} dir Directory to read
|
|
|
|
* @param {RegExp} filter Filter for the file name, only the name part is considered, not the full path
|
|
|
|
* @param {string[]=[]} arr This doesn't have to be provided, it's used for the recursion
|
|
|
|
* @param {string=dir`} rootDir Used to replace the initial path, only the relative path is left, it's faster than path.relative.
|
|
|
|
* @returns Promise array holding all relative paths
|
|
|
|
*/
|
2019-05-29 13:57:26 +02:00
|
|
|
export async function recursiveReadDir(
|
|
|
|
dir: string,
|
|
|
|
filter: RegExp,
|
|
|
|
ignore?: RegExp,
|
|
|
|
arr: string[] = [],
|
|
|
|
rootDir: string = dir
|
|
|
|
): Promise<string[]> {
|
2021-08-05 01:06:06 +02:00
|
|
|
const result = await promises.readdir(dir, { withFileTypes: true })
|
2019-02-24 22:08:35 +01:00
|
|
|
|
2019-05-29 13:57:26 +02:00
|
|
|
await Promise.all(
|
2021-08-05 01:06:06 +02:00
|
|
|
result.map(async (part: Dirent) => {
|
|
|
|
const absolutePath = join(dir, part.name)
|
|
|
|
if (ignore && ignore.test(part.name)) return
|
2019-05-09 04:51:23 +02:00
|
|
|
|
2021-08-09 17:28:00 +02:00
|
|
|
// readdir does not follow symbolic links
|
|
|
|
// if part is a symbolic link, follow it using stat
|
|
|
|
let isDirectory = part.isDirectory()
|
|
|
|
if (part.isSymbolicLink()) {
|
|
|
|
const stats = await promises.stat(absolutePath)
|
|
|
|
isDirectory = stats.isDirectory()
|
|
|
|
}
|
|
|
|
|
|
|
|
if (isDirectory) {
|
2019-05-29 13:57:26 +02:00
|
|
|
await recursiveReadDir(absolutePath, filter, ignore, arr, rootDir)
|
|
|
|
return
|
|
|
|
}
|
2019-02-24 22:08:35 +01:00
|
|
|
|
2021-08-05 01:06:06 +02:00
|
|
|
if (!filter.test(part.name)) {
|
2019-05-29 13:57:26 +02:00
|
|
|
return
|
|
|
|
}
|
2019-02-24 22:08:35 +01:00
|
|
|
|
2019-05-29 13:57:26 +02:00
|
|
|
arr.push(absolutePath.replace(rootDir, ''))
|
|
|
|
})
|
|
|
|
)
|
2019-02-24 22:08:35 +01:00
|
|
|
|
2019-07-09 03:06:04 +02:00
|
|
|
return arr.sort()
|
2019-02-24 22:08:35 +01:00
|
|
|
}
|