Skip to content

Commit

Permalink
perf: optimize flat-readdir to use fs.opendir
Browse files Browse the repository at this point in the history
  • Loading branch information
anonrig committed Jul 6, 2023
1 parent f0fc83b commit d6fdd66
Showing 1 changed file with 13 additions and 22 deletions.
35 changes: 13 additions & 22 deletions packages/next/src/lib/flat-readdir.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,20 @@
import { join } from 'path'
import { nonNullable } from './non-nullable'
import { promises } from 'fs'
import fs from 'fs/promises'

export async function flatReaddir(dir: string, includes: RegExp[]) {
const dirents = await promises.readdir(dir, { withFileTypes: true })
const result = await Promise.all(
dirents.map(async (part) => {
const absolutePath = join(dir, part.name)
if (part.isSymbolicLink()) {
const stats = await promises.stat(absolutePath)
if (stats.isDirectory()) {
return null
}
}
const dirents = await fs.opendir(dir)
const result = []

if (
part.isDirectory() ||
!includes.some((include) => include.test(part.name))
) {
return null
}
for await (const part of dirents) {
const shouldOmit =
part.isDirectory() ||
part.isSymbolicLink() ||
!includes.some((include) => include.test(part.name))

return absolutePath
})
)
if (!shouldOmit) {
result.push(join(dir, part.name))
}
}

return result.filter(nonNullable)
return result
}

0 comments on commit d6fdd66

Please sign in to comment.