2

I have a simple blog website that has a submit form and the data from that is posted on the screen, and sent as an object to my node js server. Since I want all of my existing posts to stay on the website(after refresh) I need to keep my data in JSON. I have been stuck on this part all day and can't figure it out. Here is where I think the error/ misunderstanding is.

app.post('/api', (req, res) => {
    const data = req.body;
    const words = JSON.stringify(data, null, 2);
    res.send('success')
    fs.writeFile('data.json', words, finished);
    function finished(err) {
    console.log('all set')
        }
    console.log(words) 
   }
);

What I have currently adds the data to the 'data.json' file, however whenever I try to add another post on the page, the data in the JSON file only keeps the most recent submitted data. I am a new programmer so I apologize if it is something obvious. Thanks in advance and if you need more information just ask!

seth8656
  • 104
  • 5
  • 1
    Well, sure, that's literally what writeFile is supposed to do? It obtains a file handle, writes data to that file, then closes and releases the file handle again. And if that file already existed, it'll get overwritten. If you want to _append_ to a file, do a quick google for how to append data to a file with Node, and you'll find lots of answers (and even some here on SO) that explain how to do that. – Mike 'Pomax' Kamermans Jan 02 '22 at 02:01
  • 3
    Why was this closed, append won't work here since the user is writing json, they need to read and rewrite the file. – Uzair Ashraf Jan 02 '22 at 02:07

0 Answers0