| 46 | * @returns the list of pathnames |
| 47 | */ |
| 48 | export async function recursiveReadDir( |
| 49 | rootDirectory: string, |
| 50 | options: RecursiveReadDirOptions = {} |
| 51 | ): Promise<string[]> { |
| 52 | // Grab our options. |
| 53 | const { |
| 54 | pathnameFilter, |
| 55 | ignoreFilter, |
| 56 | ignorePartFilter, |
| 57 | sortPathnames = true, |
| 58 | relativePathnames = true, |
| 59 | } = options |
| 60 | |
| 61 | // The list of pathnames to return. |
| 62 | const pathnames: string[] = [] |
| 63 | |
| 64 | /** |
| 65 | * Coerces the pathname to be relative if requested. |
| 66 | */ |
| 67 | const coerce = relativePathnames |
| 68 | ? (pathname: string) => pathname.replace(rootDirectory, '') |
| 69 | : (pathname: string) => pathname |
| 70 | |
| 71 | // The queue of directories to scan. |
| 72 | let directories: string[] = [rootDirectory] |
| 73 | |
| 74 | while (directories.length > 0) { |
| 75 | // Load all the files in each directory at the same time. |
| 76 | const results = await Promise.all( |
| 77 | directories.map(async (directory) => { |
| 78 | const result: Result = { directories: [], pathnames: [], links: [] } |
| 79 | |
| 80 | try { |
| 81 | const dir = await fs.readdir(directory, { withFileTypes: true }) |
| 82 | for (const file of dir) { |
| 83 | // If enabled, ignore the file if it matches the ignore filter. |
| 84 | if (ignorePartFilter && ignorePartFilter(file.name)) { |
| 85 | continue |
| 86 | } |
| 87 | |
| 88 | // Handle each file. |
| 89 | const absolutePathname = path.join(directory, file.name) |
| 90 | |
| 91 | // If enabled, ignore the file if it matches the ignore filter. |
| 92 | if (ignoreFilter && ignoreFilter(absolutePathname)) { |
| 93 | continue |
| 94 | } |
| 95 | |
| 96 | // If the file is a directory, then add it to the list of directories, |
| 97 | // they'll be scanned on a later pass. |
| 98 | if (file.isDirectory()) { |
| 99 | result.directories.push(absolutePathname) |
| 100 | } else if (file.isSymbolicLink()) { |
| 101 | result.links.push(absolutePathname) |
| 102 | } else if (!pathnameFilter || pathnameFilter(absolutePathname)) { |
| 103 | result.pathnames.push(coerce(absolutePathname)) |
| 104 | } |
| 105 | } |