rsnext/packages/next/lib/recursive-readdir.ts
Nick Kelly 0593dbb260
remove unecessary fs.stat calls from recursive-readdir (#27769)
## Performance improvement

- [x] Performance improvement

Removes unnecessary `fs.stat` calls in `recursiveReadDir`.

`fs.readdir` had an option `withFileTypes: boolean` added NodeJS version 10. It can be used to read the directory contents and fetch its stats simultaneously, removing the need to read individual file stats after reading the directory contents.
2021-08-04 23:06:06 +00:00

40 lines
1.2 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
if (part.isDirectory()) {
await recursiveReadDir(absolutePath, filter, ignore, arr, rootDir)
return
}
if (!filter.test(part.name)) {
return
}
arr.push(absolutePath.replace(rootDir, ''))
})
)
return arr.sort()
}