process-files-recursively
v1.0.8
Published
递归处理文件夹下的所有文件
Downloads
172
Readme
processFilesRecursively
一个轻量、稳定的 Node.js 递归文件处理工具,用于在指定目录下递归扫描 .html 文件,并执行自定义处理逻辑,同时实时输出处理统计信息。
适用于:
- 批量修改 HTML 文件
- 文案 / 品牌词替换
- 静态页面迁移
- 构建前批处理脚本
- 内部工具脚本
✨ 功能特性
- 📂 递归遍历目录
- 🎯 仅处理指定后缀文件(默认
.html) - 🚫 支持排除目录 / 文件 / 特定后缀
- ⚡ 并发处理(默认 10)
- 📊 实时输出处理进度(单行更新,不刷屏)
- 🧼 无 UI 依赖,适合 CI / 脚本环境
📦 环境要求
- Node.js >= 14
- 依赖:
npm install process-files-recursively
🚀 使用方式
1. 引入方法
const path = require('path');
const { processFilesRecursively } = require('process-files-recursively');2. 基础示例
processFilesRecursively({
folderPath: path.resolve(__dirname, './src'),
processFunction: async ({ content, filePath }) => {
const newContent = content.replace(/foo/g, 'bar');
return {
processedStr: newContent,
isChange: newContent !== content
};
}
});⚙️ 参数说明
processFilesRecursively(options)
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
| ----------------- | ---------- | ------ | -------------| -------------------------- |
| folderPath | string | ✅ | — | 需要递归扫描的根目录 |
| processFunction | Function | ✅ | — | 文件处理函数 |
| excludedFolders | string[] | ❌ | ['amtccms', 'acloud-pop', 'eula', 'blog', '.git', '.idea', 'node_modules','screenshot','xml']| 排除的目录名(仅名称匹配) |
| excludedFiles | string[] | ❌ | [] | 排除的文件名 |
| allowedSuffixes | string[] | ❌ | ['.html'] | 允许处理的文件后缀 |
| excludeSuffixes | string[] | ❌ | ['.amp.html','.html.back','.html.bak'] | 明确排除的后缀 |
| concurrency | number | ❌ | 10 | 并发处理数量 |
| openLog | boolean | ❌ | true | 是否打印日志 |
🧠 processFunction 说明
函数签名
async function processFunction({
content,
filePath
}): Promise<{
processedStr: string;
isChange: boolean;
}>参数说明
| 参数 | 类型 | 说明 |
| ---------- | -------- | ---------------- |
| content | string | 文件原始内容 |
| filePath | string | 当前文件完整路径 |
返回值说明
| 字段 | 类型 | 说明 |
| -------------- | --------- | ------------ |
| processedStr | string | 处理后的内容 |
| isChange | boolean | 是否发生修改 |
只有
isChange === true时,文件才会被写回磁盘。
📊 运行时输出示例
处理过程中(单行实时更新):
Processed: 128 | Changed: 17处理完成后:
===== Done =====
Processed files: 128
Changed files: 17函数返回结果:
const result = await processFilesRecursively(...);
console.log(result);
// { processedCount: 128, changedCount: 17 }🧪 常见使用场景
批量替换文本
processFunction: async ({ content }) => {
const next = content.replace(/OldBrand/g, 'NewBrand');
return {
processedStr: next,
isChange: next !== content
};
}只扫描不修改
processFunction: async ({ content }) => {
return {
processedStr: content,
isChange: false
};
}