Node.js使用fs模块向已有JSON文件追加内容遇问题
问题:向JSON文件追加违规记录而非覆盖内容
我正在开发一个将“违规记录(Infractions)”记录到JSON文件中以供后续使用的系统。但每次使用fs.writeFile时,都会删除整个文件并覆盖内容,我希望能向已有JSON文件中追加内容。我尝试使用fs.readFile和JSON.parse,但无法访问变量输出,一直报undefined错误。
我的代码
saveData函数
const saveData = (infraction) =>{ fs.readFile('infractions.json', function getData(err, data) { var json = JSON.parse(data) console.log(json) }) const completed = (error) = { if(error){ console.error(error) return; } } const jsonData = JSON.stringify(infraction, null, 2) setTimeout(function(){ fs.writeFile('infractions.json', jsonData,function(completed){ if(error){ console.error(error) return; } }) }, 2000); }
定义并调用函数
const infraction = { user: target.id, reason: reason, punishment: punishment } saveData(infraction);
出错的代码片段
var json = JSON.parse(data) console.log(json) })
解决方案
你的核心问题是异步逻辑处理错误,且没有将新记录与现有数据合并就直接覆盖文件。以下是修正后的实现:
推荐实现(使用async/await + fs.promises)
const fs = require('fs').promises; const path = require('path'); const saveData = async (infraction) => { const filePath = path.resolve('infractions.json'); try { // 读取现有违规记录文件 const fileContent = await fs.readFile(filePath, 'utf8'); let infractions = JSON.parse(fileContent); // 确保数据是数组(兼容文件初始为空或格式异常的情况) if (!Array.isArray(infractions)) { infractions = []; } // 追加新的违规记录 infractions.push(infraction); // 写入更新后的数组 await fs.writeFile(filePath, JSON.stringify(infractions, null, 2)); console.log('违规记录已成功追加'); } catch (err) { // 处理文件不存在的情况:创建新文件并写入第一条记录 if (err.code === 'ENOENT') { await fs.writeFile(filePath, JSON.stringify([infraction], null, 2)); console.log('首次记录:已创建新文件并写入违规信息'); } else { console.error('操作失败:', err); } } }; // 调用示例 const infraction = { user: target.id, reason: reason, punishment: punishment }; saveData(infraction);
关键修正点
- 异步逻辑同步化:使用
async/await配合fs.promises,避免回调地狱,确保读取完成后再处理数据 - 数据合并:读取现有数据后解析为数组,将新记录
push进去再写入,而非直接覆盖 - 异常处理:兼容文件不存在的场景,自动创建新文件;同时处理JSON解析失败的情况
- 语法修复:原代码中
completed函数的箭头语法错误(=改为=>)已在新实现中修正
内容的提问来源于stack exchange,提问作者ActionJackson
相关产品推荐
相关产品推荐

