How to Read a File in Deno: Simple Guide with Examples
In Deno, you can read a file using the
Deno.readTextFile function, which returns the file content as a string. Use await Deno.readTextFile('filename') inside an async function or top-level await to get the file content.Syntax
The basic syntax to read a file in Deno is using the Deno.readTextFile function. It takes the file path as a string and returns a Promise that resolves to the file content as a string.
Deno.readTextFile(path: string): Promise<string>- path: The relative or absolute path to the file you want to read.
- The function is asynchronous, so use
awaitto get the content.
typescript
const content = await Deno.readTextFile("./example.txt"); console.log(content);
Example
This example reads a file named hello.txt and prints its content to the console. It uses top-level await which is supported in Deno scripts.
typescript
const content = await Deno.readTextFile("hello.txt"); console.log("File content:", content);
Output
File content: Hello from Deno!
Common Pitfalls
Common mistakes when reading files in Deno include:
- Not running the script with
--allow-readpermission, which causes a permission error. - Using synchronous file reading methods which Deno does not provide for text files.
- Forgetting to use
awaitwithDeno.readTextFile, resulting in a Promise object instead of file content.
typescript
/* Wrong: Missing await */ const content = Deno.readTextFile("hello.txt"); console.log(content); // Prints Promise, not file content /* Right: Using await */ const contentCorrect = await Deno.readTextFile("hello.txt"); console.log(contentCorrect);
Quick Reference
Remember these tips when reading files in Deno:
- Use
Deno.readTextFilefor reading text files asynchronously. - Always run your script with
--allow-readpermission. - Use
awaitto get the file content from the Promise. - File paths can be relative or absolute.
Key Takeaways
Use Deno.readTextFile with await to read file content as a string.
Run scripts with --allow-read permission to access files.
Always await the Promise returned by Deno.readTextFile to get actual content.
File paths can be relative or absolute depending on your project structure.