deno.com

移動/重新命名檔案

在 Github 上編輯

如何在 Deno 中移動和重新命名檔案和目錄的範例。

若要重新命名或移動檔案,您可以使用 `Deno.rename` 函式。第一個引數是要重新命名的檔案路徑。第二個引數是新的路徑。
await Deno.writeTextFile("./hello.txt", "Hello World!");
await Deno.rename("./hello.txt", "./hello-renamed.txt");
console.log(await Deno.readTextFile("./hello-renamed.txt"));
如果來源檔案或目的地目錄不存在,函式將會拒絕傳回的 Promise,並產生 `Deno.errors.NotFound` 錯誤。您可以使用 `try/catch` 區塊來捕捉此錯誤。
try {
  await Deno.rename("./hello.txt", "./does/not/exist");
} catch (err) {
  console.error(err);
}
此函式的同步版本也可用。
Deno.renameSync("./hello-renamed.txt", "./hello-again.txt");
如果目的地檔案已存在,則會被覆寫。
await Deno.writeTextFile("./hello.txt", "Invisible content.");
await Deno.rename("./hello-again.txt", "./hello.txt");
console.log(await Deno.readTextFile("./hello.txt"));
執行此操作需要讀取和寫入權限。來源檔案需要可讀取,而目的地路徑需要可寫入。

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

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

您找到需要的資訊了嗎?

隱私權政策