deno.com

走訪目錄

在 Github 上編輯

當進行像是檔案系統路由之類的操作時,能夠走訪目錄以存取檔案會很有用。

如果目錄沒有深度(沒有子目錄),我們可以使用內建的 Deno.readDir
for await (const dirEntry of Deno.readDir(".")) {
  console.log("Basic listing:", dirEntry.name);
}
另一方面,如果您需要遞迴地走訪儲存庫,標準函式庫有提供對應的方法。在最簡單的情況下,它可以直接替換使用
import { walk } from "jsr:@std/fs/walk";

for await (const dirEntry of walk(".")) {
  console.log("Recursive walking:", dirEntry.name);
}
我們也可以指定一些設定來自訂結果。在建置檔案系統路由時,將結果限制為僅特定副檔名可能很有用
for await (const dirEntry of walk(".", { exts: ["ts"] })) {
  console.log("Recursive walking with extension:", dirEntry.name);
}

使用 Deno CLI 在本機執行此範例

deno run --allow-read https://deno-docs.dev.org.tw/examples/scripts/walking_directories.ts

您找到需要的資訊了嗎?

隱私權政策