Node.js脚本中如何检查文件名,避免排除资源入数组?
实现排除指定文件/文件夹的解决方案
要跳过excludedResources数组中的文件或文件夹,最简洁高效的方式是使用Array.prototype.includes()方法来快速判断当前文件名是否在排除列表内。
修改后的完整代码
const fs = require('fs-extra'); const path = require('path'); // 原代码遗漏了path模块的引入 const backupPath = path.join(__dirname, 'wp-backup'); const excludedResources = ['.DS_Store', 'dep.js', 'node_modules']; const wpFolders = []; const wpFiles = []; fs.readdir(__dirname, { withFileTypes: true }, (err, files) => { if (err) { console.error(err); // 用console.error输出错误更规范 return; } files.forEach((file) => { // 先判断是否在排除列表中,是则直接跳过后续处理 if (excludedResources.includes(file.name)) { return; } const srcPath = path.join(__dirname, file.name); const destPath = path.join(backupPath, file.name); if (file.isDirectory()) { console.log(file.name); if (!fs.existsSync(destPath)) { fs.mkdir(destPath, (err) => { if (err) { console.error(`创建目录失败: ${err}`); return; } wpFolders.push(srcPath); }); } else { // 目录已存在时也要推入数组,避免遗漏 wpFolders.push(srcPath); } } else { console.log(file.name); wpFiles.push(srcPath); } }); });
关键逻辑说明
excludedResources.includes(file.name):直接检查当前文件/文件夹名称是否在排除数组中,返回true则通过return跳过后续操作,语法简洁且可读性强。- 额外修正了原代码的几个细节问题:
- 补充了
path模块的引入(原代码使用path.join但未声明引入); - 完善了错误处理逻辑,避免创建目录失败时的静默报错;
- 补充了目录已存在时的数组推入逻辑,避免遗漏已存在的目标目录。
- 补充了
内容的提问来源于stack exchange,提问作者newbiedev
相关产品推荐
相关产品推荐

