3

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");
     }
 });
NoobCoder
  • 493
  • 8
  • 25
  • 1
    `fs.appendFile()` but you can leave out the `[ ]`. This way, while reading you can parse the file. Or, the extremely dirty way of doing it would be to read the file, parse it, add the new object to the parsed array, dump it again. – Parth Shah Jul 09 '20 at 18:29
  • 2
    Note with appendFile you have a chance of making malformed json unless you append correctly. For example if the last thing written was an object `{...}` and you append another object it would end up like `{...}{...}` which is malformed json. It is easier to read in,parse,modify, and then save. – Patrick Evans Jul 09 '20 at 18:36
  • @ParthShah leave out [ ] this way means ? I tried with appendFile(). Didn't worked – NoobCoder Jul 09 '20 at 19:30

2 Answers2

0

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.

antonku
  • 7,377
  • 2
  • 15
  • 21
-2

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.

Parth Shah
  • 1,237
  • 10
  • 24