2017-03-08 134 views
1

我有一些包含對象數組的JSON文件。我想知道如何改變這個對象的一個​​,所以改變JSON文件(覆蓋舊文件)。我知道我不能使用AngularJS來完成,但是在服務器端使用NodeJS。 這就是我想要做的事:如何使用nodejs寫入/更新新的JSON文件

--- 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的---(調用函數的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--(服務器)

//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. 
    }); 
}); 

正如你所看到的,我試圖在沒有結果的新JSON文件中編寫對象數組。

我在做什麼錯?

+0

完整代碼:https://github.com/NCozzolino/ACMovieStore.git –

+0

我不認爲我們需要您的完整代碼。事實上,你應該編輯問題和*刪除*代碼,只留下相關的位。至於「沒有結果」,你能詳細說明一下嗎?你的意思是'console'調用甚至不運行? –

+0

看這裏:http://stackoverflow.com/questions/10685998/how-to-update-a-value-in-a-json-file-and-save-it-through-node-js – Ruben

回答

0

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

編輯:

因爲fs.writefile是一個傳統的異步回調 - 你需要遵守承諾規範並返回一個新的承諾與決心,並拒絕處理,像這樣它包裝:

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

因此,在你的代碼,你將你的電話後使用像這樣的權利.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); 
    }); 
+2

爲什麼寫同步? – Sangharsh

+0

app.js怎麼樣?函數doPost()是否正確? –