0
0
DenoHow-ToBeginner ยท 3 min read

How to Use Deno.readTextFile to Read Files as Text

Use Deno.readTextFile to asynchronously read the contents of a file as a string in Deno. It takes the file path as an argument and returns a Promise that resolves to the file's text content.
๐Ÿ“

Syntax

The Deno.readTextFile function reads a file asynchronously and returns its content as a string.

  • filePath: A string representing the path to the file you want to read.
  • Returns a Promise<string> that resolves with the file content.
typescript
const text = await Deno.readTextFile(filePath);
๐Ÿ’ป

Example

This example shows how to read a file named example.txt and print its content to the console.

typescript
const filePath = "example.txt";

try {
  const content = await Deno.readTextFile(filePath);
  console.log("File content:", content);
} catch (error) {
  console.error("Error reading file:", error.message);
}
Output
File content: Hello, this is a sample text file.
โš ๏ธ

Common Pitfalls

  • Forgetting to use await or .then() to handle the asynchronous Deno.readTextFile call.
  • Not handling errors, such as when the file does not exist or permission is denied.
  • Using relative file paths without considering the current working directory.
typescript
/* Wrong: Missing await, will return a Promise object instead of file content */
const content = Deno.readTextFile("example.txt");
console.log(content); // Prints: Promise { <pending> }

/* Right: Use await to get the actual content */
const contentCorrect = await Deno.readTextFile("example.txt");
console.log(contentCorrect);
Output
Promise { <pending> } Hello, this is a sample text file.
๐Ÿ“Š

Quick Reference

Remember these key points when using Deno.readTextFile:

  • It is asynchronous and returns a Promise.
  • Use await inside an async context or handle the promise with .then().
  • Handle errors with try/catch or .catch().
  • File path must be accessible and permissions granted.
โœ…

Key Takeaways

Deno.readTextFile reads a file asynchronously and returns its content as a string.
Always use await or .then() to get the file content from the returned Promise.
Handle errors to avoid crashes when the file is missing or inaccessible.
Use correct file paths relative to the current working directory or absolute paths.
Deno requires explicit permission to read files; run with --allow-read flag.