rsnext/packages/next/lib/recursive-readdir.ts
Nick Kelly b60c943750
Remove extraneous fs.stat calls (#27779)
## Performance improvement

- [x] Performance improvement

Uses `fs.readdir`'s  `withFileTypes` option, added in NodeJS version 10,  to simultaneously read the target directories files and their stats, removing the need to call `fs.stat` on each of the files individually.

Similar to #27769, applies the same change to `recursiveCopy` and `recursiveDelete`.
2021-08-09 15:28:00 +00:00

48 lines
1.4 KiB
TypeScript

import { Dirent, promises } from 'fs'
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
*/
export async function recursiveReadDir(
dir: string,
filter: RegExp,
ignore?: RegExp,
arr: string[] = [],
rootDir: string = dir
): Promise<string[]> {
const result = await promises.readdir(dir, { withFileTypes: true })
await Promise.all(
result.map(async (part: Dirent) => {
const absolutePath = join(dir, part.name)
if (ignore && ignore.test(part.name)) return
// 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) {
await recursiveReadDir(absolutePath, filter, ignore, arr, rootDir)
return
}
if (!filter.test(part.name)) {
return
}
arr.push(absolutePath.replace(rootDir, ''))
})
)
return arr.sort()
}