如何使用fs模块在legos文件夹中查找名为cola的js文件
使用Node.js fs模块查找指定文件
场景1:仅在legos根目录查找
如果确定cola.js就在legos文件夹的根目录下,无需递归子目录,可以直接检查目标路径是否存在:
const fs = require('fs').promises; const path = require('path'); async function checkRootDir() { const targetPath = path.join(__dirname, 'legos', 'cola.js'); try { await fs.access(targetPath); console.log(`找到文件:${targetPath}`); } catch (err) { console.log(`未找到文件:${targetPath},原因:${err.message}`); } } checkRootDir();
场景2:递归遍历legos所有子目录查找
如果不确定文件位置,需要递归遍历所有层级的子目录:
const fs = require('fs').promises; const path = require('path'); async function findFileRecursive(dir, targetFilename) { const files = await fs.readdir(dir, { withFileTypes: true }); for (const file of files) { const fullPath = path.join(dir, file.name); if (file.isDirectory()) { // 递归进入子目录查找 const result = await findFileRecursive(fullPath, targetFilename); if (result) return result; } else if (file.name === targetFilename) { // 匹配到目标文件,返回完整路径 return fullPath; } } // 遍历完所有内容未找到文件 return null; } // 执行查找 (async () => { const targetDir = path.join(__dirname, 'legos'); const result = await findFileRecursive(targetDir, 'cola.js'); if (result) { console.log(`找到文件:${result}`); } else { console.log('未找到cola.js文件'); } })();
同步版本(适合简单脚本场景)
如果偏好同步阻塞式操作,可使用fs的同步API实现:
const fs = require('fs'); const path = require('path'); function findFileSync(dir, targetFilename) { const files = fs.readdirSync(dir, { withFileTypes: true }); for (const file of files) { const fullPath = path.join(dir, file.name); if (file.isDirectory()) { const result = findFileSync(fullPath, targetFilename); if (result) return result; } else if (file.name === targetFilename) { return fullPath; } } return null; } const targetDir = path.join(__dirname, 'legos'); const result = findFileSync(targetDir, 'cola.js'); if (result) { console.log(`找到文件:${result}`); } else { console.log('未找到cola.js文件'); }
说明:
- 用
path.join拼接路径可避免Windows与Unix系统的路径格式冲突 withFileTypes: true参数可直接获取文件类型,省去额外调用fs.stat的开销- 异步版本基于Promise/async-await实现,符合Node.js非阻塞IO的设计原则
内容的提问来源于stack exchange,提问作者sleepy
相关产品推荐
相关产品推荐

