Skip to content

Instantly share code, notes, and snippets.

@nebomilic
Last active December 7, 2023 14:38
Show Gist options
  • Save nebomilic/91560bafefe3ac8cea00052e6bc28439 to your computer and use it in GitHub Desktop.
Save nebomilic/91560bafefe3ac8cea00052e6bc28439 to your computer and use it in GitHub Desktop.
Async reading directory content with fs.readdir in Typescript
import fs from 'fs'
export const listFilesInDirectory = async (path: string) =>
new Promise((resolve, reject) =>
fs.readdir(path, (err, content) =>
err ? reject(err) : resolve(content)
)
)
@nebomilic
Copy link
Author

Example usage:
const listOfFilesInDirectory = await listFilesInDirectory('path/to/dir')

@andresWeitzel
Copy link

Async reading directory content with fs.readdir in Typescript (Another similar alternative way to @nebomilic)

import fs from 'fs'
export const listFilesInDirectory = async (path: string) => 
data = await new Promise((resolve, reject) =>
      fs.readdir(path, (err, content) => {
        if (err) {
          reject(err);
        }
        content.forEach((file) => {
          console.log(file);
        });
        resolve(content);
      })
    );
    return data;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment