跳至主要內容

讀寫檔案

概念

概觀

與檔案系統互動以讀取和寫入檔案是一項常見的需求。Deno 提供多種方法來透過 標準函式庫Deno 執行時間 API 來執行此操作。

擷取資料範例 中所強調的,Deno 基於安全理由預設限制存取輸入/輸出。因此,在與檔案系統互動時,必須將 --allow-read--allow-write 旗標與 deno run 命令一起使用。

讀取文字檔

Deno 執行時間 API 讓您可以透過 Deno.readTextFile() 方法來讀取文字檔,這需要一個路徑字串或 URL 物件。此方法會傳回一個承諾,提供存取檔案文字資料的權限。

命令: deno run --allow-read read.ts

/**
* read.ts
*/
const text = await Deno.readTextFile("./people.json");

console.log(text);

/**
* Output:
*
* [
* {"id": 1, "name": "John", "age": 23},
* {"id": 2, "name": "Sandra", "age": 51},
* {"id": 5, "name": "Devika", "age": 11}
* ]
*/

寫入文字檔

Deno 執行時間 API 允許開發人員透過 Deno.writeTextFile() 方法將文字寫入檔案,這需要一個檔案路徑和文字字串。此方法會傳回一個承諾,在檔案成功寫入後會解析。

若要執行命令,必須將 --allow-write 旗標提供給 deno run 命令。

指令:deno run --allow-write write.ts

/**
* write.ts
*/
await Deno.writeTextFile("./hello.txt", "Hello World!");

console.log("File written to ./hello.txt");

/**
* Output: File written to ./hello.txt
*/

您可以像這樣附加文字到檔案

await Deno.writeTextFile("./hello.txt", "This text will be appended.", {
append: true,
});

透過結合 Deno.writeTextFileJSON.stringify,您可以將序列化 JSON 物件寫入檔案。此範例使用同步 Deno.writeTextFileSync,但也可以使用 await Deno.writeTextFile 非同步執行。

若要執行程式碼,deno run 指令需要寫入標記。

指令:deno run --allow-write write.ts

/**
* write.ts
*/
function writeJson(path: string, data: object): string {
try {
Deno.writeTextFileSync(path, JSON.stringify(data));

return "Written to " + path;
} catch (e) {
return e.message;
}
}

console.log(writeJson("./data.json", { hello: "World" }));

/**
* Output: Written to ./data.json
*/