deno.com

读取文件

许多应用程序需要从磁盘读取文件。Deno 提供了一个简单的文件读取接口。

读取文件的最简单方法是将其全部内容作为字节读入内存。
const bytes = await Deno.readFile("hello.txt");
除了将文件作为字节读取,还有一个方便的函数可以将文件作为字符串读取。
const text = await Deno.readTextFile("hello.txt");
通常,您需要更多地控制文件在何时读取哪些部分。为此,您可以首先打开文件以获取一个 `Deno.FsFile` 对象。
const file = await Deno.open("hello.txt");
从文件开头读取一些字节。最多允许读取5个字节,但也要注意实际读取了多少。
const buffer = new Uint8Array(5);
const bytesRead = await file.read(buffer);
console.log(`Read ${bytesRead} bytes`);
您也可以查找文件中的已知位置并从那里读取。
const pos = await file.seek(6, Deno.SeekMode.Start);
console.log(`Sought to position ${pos}`);
const buffer2 = new Uint8Array(2);
const bytesRead2 = await file.read(buffer2);
console.log(`Read ${bytesRead2} bytes`);
您也可以使用 `seek` 将文件指针倒回开头。
await file.seek(0, Deno.SeekMode.Start);
完成后请务必关闭文件。
file.close();
也支持同步读取。
Deno.readFileSync("hello.txt");
Deno.readTextFileSync("hello.txt");
const f = Deno.openSync("hello.txt");
f.seekSync(6, Deno.SeekMode.Start);
const buf = new Uint8Array(5);
f.readSync(buf);
f.close();
读取文件需要 `-R` 权限。

使用 Deno CLI 在本地运行 此示例

deno run -R https://docs.deno.org.cn/examples/scripts/reading_files.ts

您找到所需内容了吗?

隐私政策