簡體   English   中英

如何使用 Deno 檢查文件或目錄是否存在?

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

Deno TypeScript 運行時具有內置函數,但它們都沒有解決檢查文件或目錄是否存在的問題。 如何檢查文件或目錄是否存在?

Deno API 自 Deno 1.0.0發布以來發生了變化。 如果找不到文件,則引發的異常是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

由於原始答案帳戶已暫停並且如果我對其發表評論無法更改他的答案,我正在重新發布一個固定的代碼片段。

這里有標准庫實現: 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

沒有專門用於檢查文件或目錄是否存在的函數,但是通過檢查 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

exists函數實際上是 std/fs 模塊的一部分,盡管它目前被標記為不穩定。 這意味着您需要deno run --unstablehttps ://deno.land/std/fs/README.md#exists

由於潛在的競爭條件,Deno 的 exists() 方法已被棄用,並引用了“使用時間檢查時間”漏洞。

他們建議您直接執行操作並查找錯誤。 此方法使用新建議實現了副本 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