deno.com

检查文件是否存在

在创建文件时,首先确保该文件不存在会很有用。有多种方法可以实现此目的。

使用 std 库中的 `exists` 工具来检查文件或文件夹是否存在。注意:如果在其后跟着文件操作,可能会导致竞争条件。请考虑下面的替代方案。
import { exists } from "jsr:@std/fs/exists";
await exists("./this_file_or_folder_exists"); // true
await exists("./this_file_or_folder_does_not_exist"); // false
我们还可以使用此函数来检查路径上的项是文件还是目录。
await exists("./file", { isFile: true }); // true
await exists("./directory", { isFile: true }); // false
如果在对文件执行其他操作之前直接进行检查,请勿使用上述函数。这样做会产生竞争条件。不建议将 `exists` 函数用于该用例。请考虑这种替代方案,它可以在不执行任何其他文件系统操作的情况下检查文件是否存在。
try {
  const stats = await Deno.lstat("example.txt");
} catch (err) {
  if (!(err instanceof Deno.errors.NotFound)) {
    throw err;
  }
  console.log("File does not exist");
}

使用 Deno CLI 在本地运行此示例

deno run -R -W https://docs.deno.org.cn/examples/scripts/checking_file_existence.ts

您找到所需内容了吗?

隐私政策