I know this is asked many times but I couldn't find any code for same so I am adding mine and its output. Please take a look.
app.put('/hotel/save', function(req, res) {
var fileToSave = 'savedHotelDetails.txt';
res.send('Booking Id '+guid());
res.status(200);
var arr = [];
var k;
fs.readFile(fileToSave, 'utf-8', function(err, data) {
if(err) {
k = [];
} else {
arr.push(data);
var obj = JSON.parse(req.query.params);
console.log(obj);
k = arr.push(obj);
//JSON.stringify(k);
//console.log(arr);
fs.appendFile(fileToSave, JSON.stringify(arr),'utf8');
}
})
});
This gives me output as
["",{"hotelId":"IM50003"}]["[\"\",{\"hotelId\":\"IM50003\"}]",{"hotelId":"IB50002"}]["[\"\",{\"hotelId\":\"IM50003\"}][\"[\\\"\\\",{\\\"hotelId\\\":\\\"IM50003\\\"}]\",{\"hotelId\":\"IB50002\"}]",{"hotelId":"IB50002"}]
Firstly why this kind of output? Secondaly, my goal is to make this call from front end with new data and want it to get append like
[{"ID": "IM5004"},{"ID": "IM5005"},{"ID": "IM5006"}]
The above data should be after three calls.