Shah Rukh K
Shah Rukh K

Reputation: 599

Saving Data in JSON Format using NODE

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.

Upvotes: 0

Views: 55

Answers (1)

shadowfox
shadowfox

Reputation: 581

Problem is you are reading the file content and pushing it to array and adding the new object to the array. Use file.write instead of file.append

ie instead of

 fs.appendFile(fileToSave, JSON.stringify(arr),'utf8');

use

 fs.write(fileToSave, JSON.stringify(arr),someCallbackfn)

Upvotes: 1

Related Questions