如何使用nodejs写入/更新新的JSON文件

如何使用nodejs写入/更新新的JSON文件

问题描述:

我有一些包含对象数组的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

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()是否正确? –