You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Deno中通过Deno.readDir实现目录递归读取?

在Deno中使用Deno.readDir递归读取文件

要实现递归读取目录,你可以编写一个异步递归函数,遍历目标目录的同时,对每个子目录重复执行读取操作。以下是两种常见的实现方式:

1. 直接打印所有文件/目录的完整路径

async function readDirRecursive(dir) {
  for await (const entry of Deno.readDir(dir)) {
    const fullPath = `${dir}/${entry.name}`;
    console.log(fullPath);
    // 如果当前项是目录,递归读取子目录
    if (entry.isDirectory) {
      await readDirRecursive(fullPath);
    }
  }
}

// 调用函数读取当前工作目录
await readDirRecursive(Deno.cwd());

2. 收集所有文件路径返回

如果你需要收集所有文件的路径用于后续处理,可以使用这个版本:

// 导入标准库的path模块处理路径拼接(自动适配不同系统的路径分隔符)
import * as path from "https://deno.land/std/path/mod.ts";

async function getFilesRecursive(dir) {
  const files = [];
  for await (const entry of Deno.readDir(dir)) {
    const fullPath = path.join(dir, entry.name);
    if (entry.isDirectory) {
      // 递归收集子目录的文件,合并到结果数组中
      files.push(...await getFilesRecursive(fullPath));
    } else {
      files.push(fullPath);
    }
  }
  return files;
}

// 使用示例
const allFiles = await getFilesRecursive(Deno.cwd());
console.log(allFiles);

注意事项

  • 运行脚本时需要赋予Deno读取权限,执行命令:deno run --allow-read your-script.ts

内容的提问来源于stack exchange,提问作者Tristan F.-R.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 21:25:33