如何获取Deno中DirEntry对象的完整路径?
解决Deno.readDir()获取文件完整路径的问题
Deno.readDir() 返回的 Deno.DirEntry 仅包含文件/目录的名称、类型等元数据,并未提供完整路径属性。解决方法很直接:将传入 readDir() 的基础路径,与每个 DirEntry 的 name 属性拼接即可。
推荐使用 Deno.joinPath() 完成拼接,它会自动适配不同操作系统的路径分隔符,避免手动拼接字符串出现的兼容问题。
基础读取示例
const basePath = "./your-target-folder"; // 遍历目录并生成完整路径 for await (const dirEntry of Deno.readDir(basePath)) { const fullPath = Deno.joinPath(basePath, dirEntry.name); console.log(`完整路径:${fullPath},是否为文件:${dirEntry.isFile}`); }
递归读取子目录示例
如果需要遍历所有子目录并获取完整路径,可以扩展为递归函数:
async function scanDirRecursively(basePath: string) { for await (const dirEntry of Deno.readDir(basePath)) { const fullPath = Deno.joinPath(basePath, dirEntry.name); console.log(fullPath); // 若为目录则递归处理 if (dirEntry.isDirectory) { await scanDirRecursively(fullPath); } } } // 调用递归扫描函数 await scanDirRecursively("./your-target-folder");
内容的提问来源于stack exchange,提问作者Ooker
相关产品推荐
相关产品推荐

