fs.writeFile会破坏json文件



我有一个程序,写很多文件非常快,我注意到有时会有额外的括号或json文件有时文本。以下是该程序的工作原理:有一个包含更多信息的表情符号数组,如果这个表情符号本身还没有文件,它就会创建一个新的。如果已经存在同名的文件,它将对其进行编辑。写文件的代码:

function writeToFile(fileName, file){
return new Promise(function(resolve, reject) {
fs.writeFile(fileName, JSON.stringify(file, null, 2), 'utf8', function(err) {
if (err) reject(err);
else resolve();
});
});
}

我试过使用fs和graceful-fs,它们每隔几百个文件就会出现这个问题,没有可见的模式。json:

...
],
"trade_times": []
}
]
}ade_times": []
}
]
}

第二个"ade_times"不应该在那里,我不知道为什么它出现了。其他时候它看起来像这样:

{
...
}}

没有理由地使用额外的右括号。不确定这是否是我的代码,fs或我的pc的问题。如果你需要更多的信息,我可以提供(更多的代码,node.js版本等)。谢谢你的时间:)

我不知道为什么你的代码有bug。但是,我已经为您创建了另一个writeToFile函数:

// Async functions are functions that return a promise in a more concise way.
async function writeToFile(filename, file) {
let fj = JSON.stringify(file, undefined, 2)
// fs.readFileSync will automatically reject the promise with the error when it encounters an error
fs.writeFileSync(filename, fj, {
encoding: "utf8"
})
return // This line is the equivalent of resolve(), this line is optional too.
}

希望这个答案对你有用😊

最新更新