Last active
June 27, 2025 16:12
-
-
Save ryangoree/1bd9212dc2449257570dc2fb537f7abd to your computer and use it in GitHub Desktop.
Recursively read a directory with callbacks for each file and directory.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { readdirSync, readFileSync, statSync } from "node:fs"; | |
import { join } from "node:path"; | |
export function recursiveRead({ | |
entryPath, | |
onDirectory, | |
onDirectoryExit, | |
onFile, | |
onError, | |
}: { | |
entryPath: string; | |
onDirectory?: (path: string) => void; | |
onDirectoryExit?: (path: string) => void; | |
onFile?: (content: string, path: string) => void; | |
onError?: (error: unknown) => void; | |
}) { | |
try { | |
const stat = statSync(entryPath); | |
if (stat.isFile()) { | |
const fileContent = readFileSync(entryPath, "utf8"); | |
onFile?.(fileContent, entryPath); | |
} else if (stat.isDirectory()) { | |
onDirectory?.(entryPath); | |
const childNames = readdirSync(entryPath); | |
for (const childName of childNames) { | |
const childPath = join(entryPath, childName); | |
recursiveRead({ | |
entryPath: childPath, | |
onDirectory, | |
onDirectoryExit, | |
onFile, | |
onError, | |
}); | |
} | |
onDirectoryExit?.(entryPath); | |
} | |
} catch (err) { | |
onError?.(err); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment