寫入檔案
在 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://deno-docs.dev.org.tw/examples/scripts/writing_files.ts