Skip to content

Instantly share code, notes, and snippets.

@ryangoree
Last active June 27, 2025 16:12
Show Gist options
  • Save ryangoree/1bd9212dc2449257570dc2fb537f7abd to your computer and use it in GitHub Desktop.
Save ryangoree/1bd9212dc2449257570dc2fb537f7abd to your computer and use it in GitHub Desktop.
Recursively read a directory with callbacks for each file and directory.
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