How to Use Deno.readDir to Read Directory Contents
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
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.
async function listCurrentDir() { for await (const entry of Deno.readDir(".")) { console.log(`${entry.name} - File: ${entry.isFile} - Directory: ${entry.isDirectory}`); } } listCurrentDir();
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.
/* 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
| Property | Description |
|---|---|
| entry.name | Name of the file or directory |
| entry.isFile | True if the entry is a file |
| entry.isDirectory | True if the entry is a directory |
| entry.isSymlink | True if the entry is a symbolic link |