1

I have some JSON files containing an array of objects. I would like to know how to change one of this object and so change the JSON file (overwriting the old file). I know I can't do that with AngularJS, but with NodeJS on the server-side. This is what I'm trying to do:

---Animazione.json---

[
   {
      "Locandina":"immagini/locandine/A1.jpg",
      "Titolo":"Alla ricerca di Dory",
      "Regista":"Andrew Stanton, Angus MacLane",
      "Eta":"Film per tutti",
      "Durata":"93 minuti",
      "Formato":"DVD",
      "Data":"18 gen. 2017",
      "Prezzo":"14,14€",
      "Quantita":"10"
   },
   ...

---index.html--- (call to the function doPost();)

<td><input id="clickMe" type="button" value="clickme" ng-click="doPost();" /></td>

---app.js---

App.controller('AnimazioneController', ['$scope','$http', function($scope, $http) {

                    $http.get('Animazione.json').success(function(response)
                    {
                        $scope.myData=response;
                    })
                    .error(function()
                    { 
                        alert("Si è verificato un errore!"); 
                    });

                    /*Quantita'*/
                    var dataobj =
                                {
                                    'Locandina':$scope.Locandina,
                                    'Titolo':$scope.Titolo,
                                    'Regista':$scope.Regista,
                                    'Eta':$scope.Eta,
                                    'Durata':$scope.Durata,
                                    'Formato':$scope.Formato,
                                    'Data':$scope.Data,
                                    'Prezzo':$scope.Prezzo,
                                    'Quantita':$scope.Quantita
                                };

                    $scope.doPost = function()
                    {

                      $http.post(dataobj + '/resource', {param1: 1, param2: 2});
                    };


}]);

---index.js-- (Server)

//In server (NodeJS)
var fs = require('fs'); //File system module

server.post('/resource', function(request, response)
{ //Every HTTP post to baseUrl/resource will end up here
    console.info('Updated myJSON.json');
    fs.writeFile('myJSON.json', request.body, function(err)
    {
        if (err)
        {
            console.error(err);
            return response.status(500).json(err); //Let the client know something went wrong
        }
        console.info('Updated myJSON.json');
        response.send(); //Let the client know everything's good.
    });
});

As you can see I tried to write the array of objects in a new JSON file with no results.

What am I doing wrong?

Jack
  • 25
  • 1
  • 6
  • Complete code: https://github.com/NCozzolino/ACMovieStore.git – Jack Mar 08 '17 at 12:25
  • I don't think we need your complete code. In fact, you should probably edit the question and *remove* code, leaving only the relevant bits. As of "no results", could you elaborate on that? Do you mean that `console` calls do not even run? – Álvaro González Mar 08 '17 at 12:32
  • look here: http://stackoverflow.com/questions/10685998/how-to-update-a-value-in-a-json-file-and-save-it-through-node-js – Ruben Mar 08 '17 at 12:36

1 Answers1

0

fs.writeFileSync(Animazione, JSON.stringify(content));

edit:

Because fs.writefile is a traditional asynchronous callback - you need to follow the promise spec and return a new promise wrapping it with a resolve and rejection handler like so:

  return new Promise(function(resolve, reject) {
    fs.writeFile("<filename.type>", data, '<file-encoding>', function(err) {
        if (err) reject(err);
        else resolve(data);
    });    
});

So in your code you would use it like so right after your call to .then()

.then(function(results) {
    return new Promise(function(resolve, reject) {
            fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
               if (err) reject(err);
               else resolve(data);
            });
    });
  }).then(function(results) {
       console.log("results here: " + results)
  }).catch(function(err) {
       console.log("error here: " + err);
  });
Taieb
  • 920
  • 3
  • 16
  • 37