如何在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.
相关产品推荐
相关产品推荐

