4

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");
    }
});
  • Could you include when this function is run? – Richie Bendall May 28 '22 at 04:50
  • 1
    `fs.writeFile()` will overwrite an existing file, so are you sure that `data` doesn't contain the old data? Also, is there a reason you're passing `this` as second argument to `JSON.stringify()`? – robertklep May 28 '22 at 06:20

1 Answers1

0

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 = [];