Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: Refactor recursiveReadDirSync #52517

Merged
merged 3 commits into from Jul 10, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 13 additions & 11 deletions packages/next/src/server/lib/recursive-readdir-sync.ts
@@ -1,5 +1,5 @@
import fs from 'fs'
import { join } from 'path'
import { sep } from 'path'

/**
* Recursively read directory
Expand All @@ -10,20 +10,22 @@ export function recursiveReadDirSync(
dir: string,
/** This doesn't have to be provided, it's used for the recursion */
arr: string[] = [],
/** Used to replace the initial path, only the relative path is left, it's faster than path.relative. */
rootDir = dir
/** Used to remove the initial path suffix and leave only the relative, faster than path.relative. */
rootDirLength = dir.length
): string[] {
const result = fs.readdirSync(dir, { withFileTypes: true })

result.forEach((part) => {
const absolutePath = join(dir, part.name)
// Use opendirSync for better memory usage
const result = fs.opendirSync(dir)

let part: fs.Dirent | null
while ((part = result.readSync())) {
const absolutePath = dir + sep + part.name
if (part.isDirectory()) {
recursiveReadDirSync(absolutePath, arr, rootDir)
return
recursiveReadDirSync(absolutePath, arr, rootDirLength)
} else {
arr.push(absolutePath.slice(rootDirLength))
}
arr.push(absolutePath.replace(rootDir, ''))
})
}

result.closeSync()
return arr
}