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

时间:2019-06-18 23:04:58

标签: typescript deno

Deno TypeScript运行时具有built-in functions,但是它们都不能检查文件或目录是否存在。如何检查文件或目录是否存在?

5 个答案:

答案 0 :(得分:7)

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

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

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

如果路径存在,此代码将显示true,否则显示false。

这是异步实现

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

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

确保您用unaster标志运行deno,并像这样向程序授予对该文件的访问权限

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

答案 1 :(得分:5)

自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

由于原始答案帐户已被暂停,并且如果我对其发表评论也无法更改其答案,因此我将重新发布固定代码段。

答案 2 :(得分:3)

"pubnsi": "git+https://git@github.com/naveennsit/pubs.git", 函数实际上是std / fs模块的一部分,尽管当前被标记为不稳定。这意味着您需要existshttps://deno.land/std/fs/README.md#exists

答案 3 :(得分:1)

没有专门用于检查文件或目录是否存在的功能,但是可以通过针对the Deno.stat function检查潜在的错误来使用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

答案 4 :(得分:0)

没有专门用于检查文件或目录是否存在的功能,但是可以通过针对the Deno.stat function检查潜在的错误来使用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