【发布时间】:2019-12-31 07:11:59
【问题描述】:
编辑:循环覆盖数组
我正在使用 nodejs。我想覆盖我现有的文件。运行该功能后,它会覆盖文件。将其置于循环中时,它不会覆盖文件,而是添加新内容。
参见下面的代码 sn-p。我怎样才能解决这个问题?
function writefiles() {
fs.writeFile("hello1.json", hello1, 'utf8', function (err) {
console.log("File Created");
if (err) {
console.log("An error occured while writing JSON Object to File.");
return console.log(err);
}
});
fs.writeFile("hello1.json", hello2, 'utf8', function (err) {
console.log("File Created");
if (err) {
console.log("An error occured while writing JSON Object to File.");
return console.log(err);
}
});
}
setInterval(Writefiles, 3000);
【问题讨论】:
-
@TomO.Hi,感谢您的建议,不幸的是它没有。我认为这与异步有关
-
我认为您的问题是您使用异步的
fs.writeFile。解决此问题的一种快速方法是使用fs.writeFileSync。 -
@GMartigny 谢谢你的回答我已经创建了这个 fs.writeFileSync("hello1.json", hello2, 'utf8', {'flags': 'w'} function (err) and fs .writeFileSync("hello1.json", hello2, 'utf8' function (err). 但它仍在覆盖文件
-
我觉得一定要用fs.appendFileSync,hello1和hello2必须是字符串,setInterval(Writefiles, 3000);必须设置Interval(writefiles, 3000);
-
看看the documentation for
fs.writeFileSync。您是否要覆盖您的文件?
标签: javascript node.js asynchronous