export function listRecursively(path: string): string[] { const filenames = new Set<string>(); const walk = (path: string): void => { const files = readdirSync(path); for (const file of files) { const fullPath = resolve(path, file); if (statSync(fullPath).isDirectory()) { filenames.add(fullPath + "/"); walk(fullPath); } else { filenames.add(fullPath); } } }; walk(path); return [...filenames];}
This codesnippet does below:
Initialise filenames to a Set
const filenames = new Set<string>();
Using a Set prevents duplicate file names, if you wish to include duplicate files names, you are better off using an array.
I study large open-source projects and provide insights, give my repository a star.
Define walk function with path parameter
const walk = (path: string): void => {
Get the list of files/directorites
const files = readdirSync(path);
readdirSync is an API used to read the contents of the directory. Read more about readdirSync.
Loop through files and get full path
for (const file of files) { const fullPath = resolve(path, file);
Check if the path is a directory
// statSync provides an API to check if the given path is a directory.if (statSync(fullPath).isDirectory()) { // Add the path to filenames set // filenames is a set and add is used add the fullPath filenames.add(fullPath + "/"); // Call walk function recursively walk(fullPath);} else { // filenames is a set and add is used add the fullPath filenames.add(fullPath);}
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.