0

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.

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Any "clean" way to do this?
json is just a serialization technique, if you want want persistence then try to store in a db (mongo, json-file-store) or in your case use .csv format so that you can simply append extra records without much performance penalty. refer to this stackoverflow.com/questions/24011343/…

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.