暫存檔案 & 目錄
在 Github 上編輯
暫存檔案和目錄用於儲存不打算永久保存的資料。例如,作為下載資料的本地快取。
`Deno.makeTempFile()` 函式會在預設暫存目錄中建立暫存檔案,並傳回檔案的路徑。
const tempFilePath = await Deno.makeTempFile();
console.log("Temp file path:", tempFilePath);
await Deno.writeTextFile(tempFilePath, "Hello world!");
const data = await Deno.readTextFile(tempFilePath);
console.log("Temp file data:", data);
可以指定暫存檔案的自訂前綴和後綴。
const tempFilePath2 = await Deno.makeTempFile({
prefix: "logs_",
suffix: ".txt",
});
console.log("Temp file path 2:", tempFilePath2);
也可以自訂建立暫存檔案的目錄。在這裡,我們使用相對路徑 ./tmp 目錄。
await Deno.mkdir("./tmp", { recursive: true });
const tempFilePath3 = await Deno.makeTempFile({
dir: "./tmp",
});
console.log("Temp file path 3:", tempFilePath3);
也可以建立暫存目錄。
const tempDirPath = await Deno.makeTempDir();
console.log("Temp dir path:", tempDirPath);
它具有與 `makeTempFile()` 相同的前綴、後綴和目錄選項。
const tempDirPath2 = await Deno.makeTempDir({
prefix: "logs_",
suffix: "_folder",
dir: "./tmp",
});
console.log("Temp dir path 2:", tempDirPath2);
上述函式的同步版本也可用。
const tempFilePath4 = Deno.makeTempFileSync();
const tempDirPath3 = Deno.makeTempDirSync();
console.log("Temp file path 4:", tempFilePath4);
console.log("Temp dir path 3:", tempDirPath3);
使用 Deno CLI 在本地執行此範例
deno run --allow-read --allow-write https://deno-docs.dev.org.tw/examples/scripts/temporary_files.ts