deno.com

讀取檔案

在 Github 上編輯

許多應用程式需要從磁碟讀取檔案。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();
讀取檔案需要 `--allow-read` 權限。

使用 Deno CLI 在本地執行此範例

deno run --allow-read https://deno-docs.dev.org.tw/examples/scripts/reading_files.ts

您找到需要的資訊了嗎?

隱私權政策