檢查檔案是否存在
在 Github 上編輯
在建立檔案時,先確保檔案尚不存在會很有用。有很多種方法可以做到這一點。
使用 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 --allow-read --allow-write https://deno-docs.dev.org.tw/examples/scripts/checking_file_existence.ts