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://docs.deno.org.cn/examples/scripts/walking_directories.ts

你找到你需要的东西了吗?

隐私政策