-1

编辑:循环覆盖数组

我正在使用nodejs。我想覆盖我现有的文件。运行该功能后,它会覆盖文件。将其置于循环中时,它不会覆盖文件,而是添加新内容。

请参阅下面的代码片段。我怎样才能解决这个问题?

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);
4

1 回答 1

0
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);
于 2019-12-30T20:34:37.163 回答