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-readpermission causes a permission error. - Using a regular
forloop instead offor awaitwill not work becauseDeno.readDirreturns an async iterable. - Assuming all entries are files without checking
isFileorisDirectorycan 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 awaitto loop through entries. - Check entry types with
isFile,isDirectory, andisSymlink. - Run scripts with
--allow-readpermission.
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.