2025January

List filenames recursively in a directory using this utility function.

In this article, we will review a function named listRecursively found in unbuild/src/utils.ts

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);
}
  • Call the walk function.
 walk(path);
  • Return the file names
return [...filenames];

About me:

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.

I am open to work on interesting projects. Send me an email at ramu.narasinga@gmail.com

My Github — https://github.com/ramu-narasinga

My website — https://ramunarasinga.com

My Youtube channel — https://www.youtube.com/@thinkthroo

Learning platform — https://thinkthroo.com

Codebase Architecture — https://app.thinkthroo.com/architecture

Best practices — https://app.thinkthroo.com/best-practices

Production-grade projects — https://app.thinkthroo.com/production-grade-projects

References

  1. https://github.com/unjs/unbuild/blob/main/src/utils.ts#L54

  2. https://nodejs.org/api/fs.html#fsreaddirsyncpath-options

  3. https://nodejs.org/api/fs.html#fsstatsyncpath-options

We use cookies
We use cookies to ensure you get the best experience on our website. For more information on how we use cookies, please see our cookie policy.

By clicking "Accept", you agree to our use of cookies.

Learn more