乐闻世界logo
搜索文章和话题

How do I read a local file in Deno?

1个答案

1

Reading local files in Deno is a straightforward and relatively simple process, primarily through the API provided by Deno's standard library. Below, I will detail a common method for reading local text files.

Step 1: Ensure Deno is Installed

First, verify that Deno is installed on your system. You can check this by running the following command in the command line:

bash
deno --version

If Deno is installed, this command will display the version number.

Step 2: Write Code to Read Files

In Deno, use the Deno.readTextFile function to asynchronously read the contents of a text file. This function returns a Promise that resolves with the entire file content. Here is a simple example:

typescript
// Example code to read a file async function readFile(filePath: string) { try { const content = await Deno.readTextFile(filePath); console.log("File content:", content); } catch (error) { console.error("Error reading file:", error); } } // Using the function to read a file readFile("./example.txt");

In this example, the readFile function accepts a file path as a parameter and attempts to read the file. If successful, it outputs the file content; if an error occurs, it catches and displays the error message.

Step 3: Run Your Deno Program

To execute the above Deno program, run the following command in the command line, ensuring the program has the necessary permissions to access the file system:

bash
deno run --allow-read example.ts

The --allow-read flag is required because Deno defaults to a secure mode that restricts file system access unless explicitly granted.

Summary

This example demonstrates reading local files in Deno. Through simple API calls and Deno's secure default settings (requiring explicit permissions), file reading operations are both secure and manageable. Use Deno.readTextFile for text files and Deno.readFile for binary files.

2024年7月20日 18:55 回复

你的答案