循环创建文件,添加文件而不是覆盖

时间:2019-12-30 19:59:35

标签: javascript node.js asynchronous

编辑:遍历整个数组

我正在使用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);

1 个答案:

答案 0 :(得分: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);