![](/img/trans.png)
[英]How to Read a JSON file,and change some values and write the json in to new file in nodejs
[英]How to write/update new JSON file with nodejs
我有一些包含對象數組的JSON文件。 我想知道如何更改此對象之一,因此更改JSON文件(覆蓋舊文件)。 我知道我不能用AngularJS做到這一點,但在服務器端使用NodeJS。 這就是我想要做的:
--- 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文件中編寫對象數組,但沒有結果。
我究竟做錯了什么?
fs.writeFileSync(Animazione,JSON.stringify(content));
編輯:
因為fs.writefile是一個傳統的異步回調 - 你需要遵循promise規范並返回一個新的聲明,它包含一個解析和拒絕處理程序,如下所示:
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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.