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 protected]",
    "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");
     }
 });
3
  • 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. Commented Jul 9, 2020 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. Commented Jul 9, 2020 at 18:36
  • @ParthShah leave out [ ] this way means ? I tried with appendFile(). Didn't worked Commented Jul 9, 2020 at 19:30

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Tried this. Didn't appended.
-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.

1 Comment

Don't want to read the data again.

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.