How to avoid overwrite of existing file json object in node

Viewed 2934

I am trying to solve an issue where I am trying to write a json file with user input details. But each time I input new details it is overwriting the existing data.

How can I avoid overwriting existing json object in a json file and add new object in the array instead based on user input ?

userData.json:

[
  {
    "name": "Name",
    "number": "4334343",
    "email": "email@email.com",
    "message": "sdsd"
  }
]

server.js :-

app.get("/myaction", function (request, response){
     var name = request.query.name;
     var number = request.query.number;
     var email = request.query.email;
     var message = request.query.message;
 
     if (name != "") {
         response.send("Your name is " + name + "number"+ number + "email"+ email + "message" + message);

        const sendData = [{
            name:name,
            number:number,
            email:email,
            message:message
        }];

        fs.stat('./userdata.json', function(err, stat) {
            if(err == null) {
                console.log('File exists');
            } else if(err.code === 'ENOENT') {
                
                // file does not exist
                var data = JSON.stringify(sendData,null, 2);
                fs.writeFile('./userdata.json', data, (err) => {
                    if (!err) {
                        console.log('done');
                    }
                });
            } else {
                console.log('Some other error: ', err.code);
            }
        });
     } else {
         response.send("Please provide info");
     }
 });
2 Answers

In order to append data instead of replacing it you can pass a+ flag to fs.writeFile:

fs.writeFile('./userdata.json', data, { flag: 'a+' }, (err) => {
  if (!err) {
    console.log('done');
  }
});

It will create the file if the file does not exist. If the file exists, then the content will be appended.

Here is the dirty way to do it:

fs.readFile('./userdata.json', (err, data) => {
    if (err){
        console.log(err);
    } else {
        obj = JSON.parse(data);
        obj.push(sendData);
        json = JSON.stringify(obj); 
        fs.writeFile('./userdata.json', json, callback);
}});

Everytime you want to add a record, read the array, append to it and dump it again. However, consider switching to a database to avoid this.

Related