NodeJS: Write to JSON file removes existing data

511 Views Asked by At

I am working on this method:

router.use(bodyparser.json());
router.post('/', (req, res) => {

    let rooms;
    //let roomID = methoden.idErstellen(rooms, filename);

    try {
        rooms = {
            //id: roomID,
            id:req.body.id,
            name: req.body.name
        };
        //createRessource(filename)
        let data = JSON.stringify(rooms, null, 2);
        fs.writeFile(filename, data, (err)=> {
            if(err) throw err;
            console.log('Data written to file')
        });
        //res.status(201).send(rooms);
    } catch (error) {
        res.sendStatus(500)
    }
    refresh();
});

The method adds a new data set to the JSON file, but removes all the existing ones. I can't figure out what the problem with this is

1

There are 1 best solutions below

1
Ryan On

Try using fs.appendFile

fs.appendFile(filename, data, function (err) {
  if (err) throw err;
  console.log('Data written to file successfully');
});