Skip to content Skip to sidebar Skip to footer

Add Object To An Array In A Json `file` In Node.js For Each Request

I have an image on the frontend. When the user right clicks on the image, the coordinates of that point are stored in a variable and that variable is then sent to the node server u

Solution 1:

fs.writeFile: Asynchronously writes data to a file, replacing the file if it already exists.

fs.appendFile: Asynchronously append data to a file, creating the file if it does not yet exist.

Solution 2:

Code has two issues,

use appendFile instead of writeFile, modified the code below. Also you need to send the response once the write is completed.

function finished(err){ console.log('all set.'); response.send("All OK"); }

Otherwise response might go earlier before the write is completed.

.post(function(request, response){
    console.log("Request received");
    var util = require('util');
    var coordinates = request.body;
    var imageCoordinates = JSON.stringify(coordinates);
    fs.appendFile('coords.json', imageCoordinates, finished);

    functionfinished(err){
        console.log('all set.');
        response.send("All OK");
    }

    console.log('coords are:', coordinates);        

}); 

Post a Comment for "Add Object To An Array In A Json `file` In Node.js For Each Request"