deno.com

移动/重命名文件

在 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 -R=./ -W=./ https://docs.deno.org.cn/examples/scripts/moving_renaming_files.ts

您找到所需内容了吗?

隐私政策