0
0
DenoHow-ToBeginner ยท 3 min read

How to Use Deno.readDir to Read Directory Contents

Use Deno.readDir(path) to asynchronously read the contents of a directory at path. It returns an async iterable of directory entries, each with details like name and type. You can loop over it with for await to process each entry.
๐Ÿ“

Syntax

The Deno.readDir function takes a single argument path, which is the directory path you want to read. It returns an async iterable of Deno.DirEntry objects representing each item inside the directory.

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

  • path: string path to the directory
  • returns: async iterable of directory entries
typescript
for await (const entry of Deno.readDir(path)) {
  console.log(entry.name, entry.isFile, entry.isDirectory);
}
๐Ÿ’ป

Example

This example reads the current directory "." and prints the name and type of each entry.

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

listCurrentDir();
Output
example.txt - File: true - Directory: false src - File: false - Directory: true README.md - File: true - Directory: false
โš ๏ธ

Common Pitfalls

1. Forgetting to use for await: Deno.readDir returns an async iterable, so you must use for await to loop over it. Using a normal for loop will not work.

2. Not handling permissions: Reading directories requires --allow-read permission when running your Deno script.

3. Assuming synchronous behavior: Deno.readDir is asynchronous and non-blocking, so do not treat it like a synchronous function.

typescript
/* Wrong way: missing 'await' in loop */
for (const entry of Deno.readDir(".")) {
  console.log(entry.name); // This will cause an error
}

/* Right way: use 'for await' */
for await (const entry of Deno.readDir(".")) {
  console.log(entry.name);
}
๐Ÿ“Š

Quick Reference

PropertyDescription
entry.nameName of the file or directory
entry.isFileTrue if the entry is a file
entry.isDirectoryTrue if the entry is a directory
entry.isSymlinkTrue if the entry is a symbolic link
โœ…

Key Takeaways

Use for await to loop over the async iterable returned by Deno.readDir.
Deno.readDir requires --allow-read permission to access directories.
Each entry provides useful properties like name, isFile, and isDirectory.
Deno.readDir is asynchronous and non-blocking, so handle it with async code.
Always handle errors or permission issues when reading directories.