0
0
DenoHow-ToBeginner ยท 3 min read

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 await to 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-read permission, which causes a permission error.
  • Using synchronous file reading methods which Deno does not provide for text files.
  • Forgetting to use await with Deno.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.readTextFile for reading text files asynchronously.
  • Always run your script with --allow-read permission.
  • Use await to 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.