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");
}
});
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.{...}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.