如何使用Node.js将包含JSON文件的目录树转换为单个整合JSON文件
Node.js 实现目录转单JSON文件方案
核心处理步骤
- 遍历CMS根目录,递归读取所有子文件,过滤出后缀为
.json的文件,排除非JSON格式文件 - 拆分每个JSON文件的相对路径,移除根目录前缀和
.json后缀,得到层级节点数组,比如CMS/en/brand_one/footer.json处理后得到['en', 'brand_one', 'footer'] - 按照层级节点把读取到的JSON内容挂载到最终结果对象的对应位置:第一层是语言标识(如en、de),对应值为数组,数组内第一个元素存放所有品牌配置;第二层是品牌名,第三层是footer/header,对应值为对应JSON文件的内容
- 增加异常处理逻辑:捕获文件读取失败、JSON格式错误等异常,避免单个文件问题导致整个程序终止
- 把组装完成的结果对象格式化后写入到指定的
content.json文件中
实现代码(零第三方依赖版)
直接用Node.js内置的fs/promises和path模块即可实现,不需要安装额外依赖,性能最优:
const fs = require('fs/promises'); const path = require('path'); // 配置项 const ROOT_DIR = path.join(__dirname, 'CMS'); // CMS目录路径 const OUTPUT_FILE = path.join(__dirname, 'content.json'); // 输出文件路径 // 递归遍历目录获取所有JSON文件 async function getAllJsonFiles(dir, fileList = []) { const files = await fs.readdir(dir, { withFileTypes: true }); for (const file of files) { const fullPath = path.join(dir, file.name); if (file.isDirectory()) { await getAllJsonFiles(fullPath, fileList); } else if (file.isFile() && path.extname(file.name) === '.json') { fileList.push(fullPath); } } return fileList; } async function main() { const result = {}; const jsonFiles = await getAllJsonFiles(ROOT_DIR); for (const filePath of jsonFiles) { try { // 计算相对路径,拆分层级 const relativePath = path.relative(ROOT_DIR, filePath); const pathSegments = relativePath.split(path.sep); // 移除.json后缀得到最后一个层级名 pathSegments[pathSegments.length - 1] = path.basename(pathSegments[pathSegments.length - 1], '.json'); const [lang, brand, type] = pathSegments; // 初始化层级结构 if (!result[lang]) result[lang] = [{}]; if (!result[lang][0][brand]) result[lang][0][brand] = {}; // 读取JSON内容挂载 const fileContent = await fs.readFile(filePath, 'utf-8'); result[lang][0][brand][type] = JSON.parse(fileContent); } catch (err) { console.error(`处理文件${filePath}失败:`, err.message); } } // 写入输出文件,格式化缩进2空格 await fs.writeFile(OUTPUT_FILE, JSON.stringify(result, null, 2), 'utf-8'); console.log('content.json 生成完成'); } main().catch(err => console.error('程序运行失败:', err));
精简版实现(使用glob模块)
如果需要更简洁的代码,可以安装glob模块快速匹配所有JSON文件:
- 先安装依赖:
npm i glob - 代码示例:
const fs = require('fs/promises'); const path = require('path'); const { glob } = require('glob'); const ROOT_DIR = path.join(__dirname, 'CMS'); const OUTPUT_FILE = path.join(__dirname, 'content.json'); async function main() { const result = {}; // 匹配所有CMS目录下的json文件 const jsonFiles = await glob('**/*.json', { cwd: ROOT_DIR, absolute: true }); for (const filePath of jsonFiles) { try { const relativePath = path.relative(ROOT_DIR, filePath); const [lang, brand, fileName] = relativePath.split(path.sep); const type = path.basename(fileName, '.json'); if (!result[lang]) result[lang] = [{}]; if (!result[lang][0][brand]) result[lang][0][brand] = {}; const content = await fs.readFile(filePath, 'utf-8'); result[lang][0][brand][type] = JSON.parse(content); } catch (err) { console.error(`处理${filePath}失败:`, err.message); } } await fs.writeFile(OUTPUT_FILE, JSON.stringify(result, null, 2), 'utf-8'); } main().catch(console.error);
内容的提问来源于stack exchange,提问作者derp
相关产品推荐
相关产品推荐

