如何使用 Deno 检查文件或目录是否存在?

How can one check if a file or directory exists using Deno?

Deno TypeScript 运行时有 built-in functions,但其中 none 解决了检查文件或目录是否存在的问题。如何检查文件或目录是否存在?

没有专门检查文件或目录是否存在的函数,但是the Deno.stat function, which returns metadata about a path, can be used for this purpose by checking the potential errors against Deno.ErrorKind.NotFound.

const exists = async (filename: string): Promise<boolean> => {
  try {
    await Deno.stat(filename);
    // successful, file or directory must exist
    return true;
  } catch (error) {
    if (error && error.kind === Deno.ErrorKind.NotFound) {
      // file or directory does not exist
      return false;
    } else {
      // unexpected error, maybe permissions, pass it along
      throw error;
    }
  }
};

exists("test.ts").then(result =>
  console.log("does it exist?", result)); // true

exists("not-exist").then(result =>
  console.log("does it exist?", result)); // false

自 Deno 1.0.0 发布以来,Deno API 发生了变化。如果找不到文件,则引发的异常是 Deno.errors.NotFound

const exists = async (filename: string): Promise<boolean> => {
  try {
    await Deno.stat(filename);
    // successful, file or directory must exist
    return true;
  } catch (error) {
    if (error instanceof Deno.errors.NotFound) {
      // file or directory does not exist
      return false;
    } else {
      // unexpected error, maybe permissions, pass it along
      throw error;
    }
  }
};

exists("test.ts").then(result =>
  console.log("does it exist?", result)); // true

exists("not-exist").then(result =>
  console.log("does it exist?", result)); // false

As the original answer account is suspended and cannot change his answer if I comment on it, I'm reposting a fixed code snippet.

exists 函数实际上是 std/fs 模块的一部分,尽管它目前被标记为不稳定。这意味着您需要 deno run --unstable: https://deno.land/std/fs/README.md#exists

这里有标准库实现:https://deno.land/std/fs/mod.ts

import {existsSync} from "https://deno.land/std/fs/mod.ts";

const pathFound = existsSync(filePath)
console.log(pathFound)

如果路径存在,此代码将打印 true,如果不存在,则打印 false

这是异步实现:

import {exists} from "https://deno.land/std/fs/mod.ts"

exists(filePath).then((result : boolean) => console.log(result))

确保你 运行 使用不稳定标志 deno 并授予对该文件的访问权限:

deno run --unstable  --allow-read={filePath} index.ts