2

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");
    }
});
2
  • Could you include when this function is run? Commented May 28, 2022 at 4: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()? Commented May 28, 2022 at 6:20

1 Answer 1

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 = [];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.