javascript - 如何使用 Node.js 编写/更新新的 JSON 文件

标签 javascript angularjs json node.js

我有一些包含对象数组的 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 规范并返回一个新的 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);
  });

关于javascript - 如何使用 Node.js 编写/更新新的 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42671321/

相关文章:

php - angularJS $http.get() 对复杂 JSON 输出的请求

javascript - 如何使用正则表达式来匹配对象键并替换为其值?

javascript - 有没有办法将变量从 client.js 文件发送到您的 node.js 文件?

javascript - 如何检查复选框是否未被选中

javascript - FireFox editableCellTemplate 只允许编辑一次

javascript - AngularJs 覆盖工具提示 bootstrap.css 样式

c# - 如何使用 WebBrowser 控件捕获 JSON 响应

Javascript 将表单序列化为 JSON

java - 如何解析来自 Unirest 调用的 JSON 结果

javascript - 如何 append 到最近的 div(按类)?