NodeJS如何搜索文件夹及其子文件夹下的特定文件并获取对应路径?
递归搜索指定文件函数实现方案
前置依赖
直接使用Node.js内置的fs和path模块即可,无需引入第三方依赖,不会增大你的npm包体积。
核心实现思路
- 读取目标目录下的所有文件/目录条目
- 遇到目录就递归进入遍历
- 遇到文件就匹配文件名,匹配成功直接返回完整路径
- 遍历完所有层级未匹配到则返回空值
同步版本(适合CLI、轻量场景)
适合不需要考虑阻塞主线程的场景,调用更简单:
const fs = require('fs') const path = require('path') /** * 递归搜索指定文件 * @param {string} filename 要查找的目标文件名 * @param {string} [searchRoot=process.cwd()] 搜索根目录,默认当前工作目录 * @returns {string|undefined} 匹配到的文件完整路径,未找到返回undefined */ function findFile(filename, searchRoot = process.cwd()) { const entries = fs.readdirSync(searchRoot, { withFileTypes: true }) for (const entry of entries) { const fullPath = path.join(searchRoot, entry.name) if (entry.isDirectory()) { // 跳过常见不需要遍历的目录,不需要可以删除 if (['node_modules', '.git', '.vscode'].includes(entry.name)) continue const foundPath = findFile(filename, fullPath) if (foundPath) return foundPath } else if (entry.isFile() && entry.name === filename) { return fullPath } } return undefined } // 调用示例 const configPath = findFile('config.json')
异步Promise版本(适合服务端、高性能场景)
不会阻塞主线程,适合对性能要求高的场景:
const fs = require('fs/promises') const path = require('path') async function findFileAsync(filename, searchRoot = process.cwd()) { const entries = await fs.readdir(searchRoot, { withFileTypes: true }) for (const entry of entries) { const fullPath = path.join(searchRoot, entry.name) if (entry.isDirectory()) { if (['node_modules', '.git', '.vscode'].includes(entry.name)) continue const foundPath = await findFileAsync(filename, fullPath) if (foundPath) return foundPath } else if (entry.isFile() && entry.name === filename) { return fullPath } } return undefined } // 调用示例 const configPath = await findFileAsync('config.json')
可选优化项
- 如需返回所有匹配到的文件路径而非第一个,可定义数组存储结果,遍历完成后返回数组
- 如需支持模糊匹配,可将入参改为正则,匹配时用
entry.name.match(正则规则)判断 - 可添加try/catch逻辑捕获目录读取权限错误,避免遍历中途崩溃
内容的提问来源于stack exchange,提问作者Human Friend
相关产品推荐
相关产品推荐

