fs.writeFile (node) adds information on an already existing file instead of replacing this

Viewed 73

I made a code to write a file using fs and node-cron to run this every x minutes. I get the data the first time, but in the next job I get the data added again in the file and the old one too, I wan to create a new file and replace the old one (and the previous information) but I still have this appended instead of only the new data,

fs.writeFile(path.join(__dirname, '_data', 'data.json'), JSON.stringify(data, this, 2), {flag: 'w'}, err => {
    if (err) {
        console.error(err);
    } else {
        console.log("Success");
    }
});
1 Answers

I was able to understand my error, I should initialize again variable data in order to clear previous results.

    //Save data into fs
    fs.writeFile(path.join(__dirname, '_data', 'varlix.json'), JSON.stringify(varlix, this, 2), err => {
        if (err) {
            console.error(err);
        } else {
            console.log("Success");
        }
    });
    data = [];
Related