deno.com

写入文件

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

写入文件最简单的方法是将整个缓冲区一次性写入文件中。这是一个将字节数组写入文件的简单示例。
const bytes = new Uint8Array([72, 101, 108, 108, 111]);
await Deno.writeFile("hello.txt", bytes, { mode: 0o644 });
你也可以写入字符串而不是字节数组。
await Deno.writeTextFile("hello.txt", "Hello World");
或者你可以将二进制数据作为字符串写入。
await Deno.writeTextFile("hello.txt", "Hello World", { encoding: "utf8" });
要追加到文本文件,请将 `append` 参数设置为 `true`。
await Deno.writeTextFile("server.log", "Request: ...", { append: true });
也支持同步写入。
Deno.writeFileSync("hello.txt", bytes);
Deno.writeTextFileSync("hello.txt", "Hello World");
对于更精细的写入,请打开一个新文件进行写入。
const file = await Deno.create("hello.txt");
你可以将数据块写入文件。
const written = await file.write(bytes);
console.log(`${written} bytes written.`);
`file.write` 返回写入的字节数,因为它可能不会写入所有传入的字节。我们可以获取一个 Writer 来确保整个缓冲区都被写入。
const writer = file.writable.getWriter();
await writer.write(new TextEncoder().encode("World!"));
关闭写入器会自动关闭文件。如果你不使用写入器,请确保在使用完毕后关闭文件。
await writer.close();
写入文件需要 `-W` 权限。

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

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

您找到所需内容了吗?

隐私政策