上一章讲了如何把多个json文件合并成一个db.json文件,没看的小伙伴可以点击查看JSON-SERVER实现多文件合并
但是呢,在使用过程中发现,一旦我们对数据进行 更新 删除 添加db.json数据是进去了,但是对应的json文件的内容没有更新,这样就导致子json文件和db.json里的数组数据对不上,所有我又写了一个脚本,可以监听db.json里面数组的数据变化,db.json里面的数据一旦变化,我们可以执行该脚本,让db.json里面更新的数据自动添加到对应的子json文件中
代码如下
const fs = require('fs');
const path = require('path');
// 读取JSON文件内容
function readJsonFile(filePath) {
try {
const data = fs.readFileSync(filePath, 'utf8');
return JSON.parse(data);
} catch (error) {
console.error(`读取文件错误 ${filePath}:`, error);
return null;
}
}
// 写入JSON文件内容
function writeJsonFile(filePath, content) {
try {
const data = JSON.stringify(content, null, 2); // 格式化输出
fs.writeFileSync(filePath, data, 'utf8');
console.log(`文件 ${filePath} 更新.`);
} catch (error) {
console.error(`写入文件错误 ${filePath}:`, error);
}
}
// 主函数
function main() {
const dbFilePath = '../server/db.json';//从哪里读取db.json文件
const dbData = readJsonFile(dbFilePath);
if (!dbData) {
console.error('读取db.json失败');
return;
}
// 指定要写入文件的文件夹路径
const outputDir = '../server'; // 这里是您的文件夹路径
// 确保文件夹存在
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir);
}
// 遍历db.json中的所有数组
for (const key in dbData) {
if (Array.isArray(dbData[key])) { // 确保是数组
const outputFileName = `${key}.json`; // 生成输出文件名
const outputFilePath = path.join(outputDir, outputFileName); // 使用path.join来构建完整的文件路径
const previousData = readJsonFile(outputFilePath);
const currentData = {
[key]: dbData[key]
}; // 创建一个对象,其中包含当前的数组
// 如果文件不存在或内容不同,则更新文件
if (!previousData || JSON.stringify(previousData) !== JSON.stringify(currentData)) {
writeJsonFile(outputFilePath, currentData);
} else {
console.log(`文件 ${outputFilePath} 未更新,内容相同.`);
}
}
}
}
// 运行主函数
main();
当我们每次更新了db.json文件后,我们只需要执行该js文件 就可以把db.json里面的数组数据更新到对应的子json文件中