简体   繁体   English

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

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

The Deno TypeScript runtime has built-in functions , but none of them address checking the existence of a file or directory. Deno TypeScript 运行时具有内置函数,但它们都没有解决检查文件或目录是否存在的问题。 How can one check if a file or directory exists?如何检查文件或目录是否存在?

The Deno API changed since the release of Deno 1.0.0 . Deno API 自 Deno 1.0.0发布以来发生了变化。 If the file is not found the exception raised is Deno.errors.NotFound如果找不到文件,则引发的异常是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.由于原始答案帐户已暂停并且如果我对其发表评论无法更改他的答案,我正在重新发布一个固定的代码片段。

There is the standard library implementation, here: https://deno.land/std/fs/mod.ts这里有标准库实现: https ://deno.land/std/fs/mod.ts

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

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

This code will print true if the path exists and false if not.如果路径存在,则此代码将打印true ,否则将打印false

And this is the async implementation:这是异步实现:

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

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

Make sure you run deno with the unstable flag and grant access to that file:确保使用不稳定标志运行 deno 并授予对该文件的访问权限:

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

There is no function that's specifically for checking if a file or directory exists, but 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 .没有专门用于检查文件或目录是否存在的函数,但是通过检查 Deno.ErrorKind.NotFound 的潜在错误,可以将返回有关路径的元数据的Deno.stat函数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

The exists function is actually part of the std/fs module although it is currently flagged as unstable. exists函数实际上是 std/fs 模块的一部分,尽管它目前被标记为不稳定。 That means you need to deno run --unstable : https://deno.land/std/fs/README.md#exists这意味着您需要deno run --unstablehttps ://deno.land/std/fs/README.md#exists

Deno's exist() method has been deprecated due to potential race conditions, and cites a 'Time-of-check to time-of-use' exploit.由于潜在的竞争条件,Deno 的 exists() 方法已被弃用,并引用了“使用时间检查时间”漏洞。

They suggest you perform the operation directly and look for errors.他们建议您直接执行操作并查找错误。 This method achieves replicates exist() using the new recommendation:此方法使用新建议实现了副本 exists():

async function exists(file: string) {
    try {
        await Deno.stat(file);
    }
    
    catch(e) {
        if(e instanceof Deno.errors.NotFound) {
            return false;
        }
    }
    
    return true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM