0
0
DenoHow-ToBeginner ยท 3 min read

How to Read Directory in Deno: Simple Guide with Examples

In Deno, you can read a directory using the Deno.readDir function, which returns an async iterable of directory entries. Use a for await loop to iterate over each entry and access its properties like name and isFile. Remember to run your script with --allow-read permission to access the file system.
๐Ÿ“

Syntax

The Deno.readDir(path) function reads the directory at the given path and returns an async iterable of directory entries. Each entry has properties like name (file or folder name), isFile, isDirectory, and isSymlink.

You use for await (const entry of Deno.readDir(path)) to loop through the entries asynchronously.

typescript
for await (const entry of Deno.readDir("./some-directory")) {
  console.log(entry.name, entry.isFile, entry.isDirectory);
}
๐Ÿ’ป

Example

This example reads the current directory and prints each entry's name and type (file or directory). It demonstrates how to use Deno.readDir with async iteration and how to check entry types.

typescript
async function readCurrentDir() {
  for await (const entry of Deno.readDir(".")) {
    if (entry.isFile) {
      console.log(`File: ${entry.name}`);
    } else if (entry.isDirectory) {
      console.log(`Directory: ${entry.name}`);
    } else {
      console.log(`Other: ${entry.name}`);
    }
  }
}

readCurrentDir();
Output
File: example.txt Directory: src File: README.md
โš ๏ธ

Common Pitfalls

  • Not running the script with --allow-read permission causes a permission error.
  • Using a regular for loop instead of for await will not work because Deno.readDir returns an async iterable.
  • Assuming all entries are files without checking isFile or isDirectory can cause logic errors.
typescript
/* Wrong: Missing --allow-read permission will cause error */
// Run with: deno run --allow-read script.ts

/* Wrong: Using for loop instead of for await */
const entries = Deno.readDir(".");
for (const entry of entries) { // โŒ This will not work
  console.log(entry.name);
}

/* Right: Use for await */
for await (const entry of Deno.readDir(".")) { // โœ… Correct
  console.log(entry.name);
}
๐Ÿ“Š

Quick Reference

Remember these key points when reading directories in Deno:

  • Use Deno.readDir(path) to get async iterable entries.
  • Use for await to loop through entries.
  • Check entry types with isFile, isDirectory, and isSymlink.
  • Run scripts with --allow-read permission.
โœ…

Key Takeaways

Use Deno.readDir with for await to asynchronously read directory entries.
Always run your Deno script with --allow-read permission to access the file system.
Check entry properties like isFile and isDirectory to handle files and folders correctly.
Avoid using regular for loops with Deno.readDir because it returns an async iterable.
Handle permission errors by granting the correct read access when running your script.