如何使用Node.js编写/更新新的JSON文件 [英] How to write/update new JSON file with nodejs

查看:79
本文介绍了如何使用Node.js编写/更新新的JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些包含对象数组的JSON文件.我想知道如何更改此对象之一,然后更改JSON文件(覆盖旧文件).我知道我无法使用AngularJS做到这一点,但是可以通过服务器端的NodeJS做到这一点. 这就是我想要做的:

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 ---

---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();)

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

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

-app.js ---

---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--(服务器)

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

如您所见,我试图在新的JSON文件中写入对象数组,但没有结果.

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

我在做什么错了?

推荐答案

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

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

因为fs.writefile是传统的异步回调-您需要遵循promise规范并返回一个新的promise,将它包装为一个解析和拒绝处理程序,如下所示:

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

因此在您的代码中,您将在调用.then()

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

这篇关于如何使用Node.js编写/更新新的JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆