【问题标题】:Creating files in loop, adding files instead of overwriting循环创建文件,添加文件而不是覆盖
【发布时间】: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


【解决方案1】:
function writefiles() {
fs.appendFileSync("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.appendFileSync("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);

【讨论】:

  • 感谢您的反馈,我不想附加到要覆盖的文件中
  • 试试这个 fs.writeFileSync(path,content,{encoding:'utf8',flag:'w'})
猜你喜欢
  • 1970-01-01
  • 2015-07-25
  • 2015-06-20
  • 2016-06-19
  • 1970-01-01
  • 1970-01-01
  • 2021-02-05
  • 2015-08-20
  • 1970-01-01
相关资源
最近更新 更多