写入文件
在 Github 上编辑
许多应用程序需要将文件写入磁盘。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");
要追加到文本文件,请将 `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!"));
关闭 writer 会自动关闭文件。如果您不使用 writer,请确保在使用完文件后关闭它。
await writer.close();
写入文件需要 `--allow-write` 权限。
使用 Deno CLI 在本地运行此示例
deno run --allow-read --allow-write https://docs.deno.org.cn/examples/scripts/writing_files.ts