【问题标题】:Saving JSON data correctly on nodeJS server在 nodeJS 服务器上正确保存 JSON 数据
【发布时间】:2019-06-26 20:33:01
【问题描述】:

我仍在处理我的 SPA,我可以在哪里跟踪我的费用。每个费用项目由一个值、一个日期、描述和标签组成。

客户端将所有这些数据发送到我的服务器,我想将其保存在 JSON 文件中。

我的代码现在看起来像这样: (json.push 不起作用)

        client.on('message', function(value, date, descr, tags) {
        console.log('message: ' + value, date, descr, tags );

        var exp = new Object();
        exp.id = id;
        exp.value = value;
        exp.date = date;
        exp.tags = tags;
        expArr[exp.id] = exp;
        id++;
        console.log(exp.id);



        fs.readFile('expenses.json', function (err, data) {
             var json = JSON.parse(data);
             json.push(exp);
             console.log(json);
             fs.writeFile("expenses.json", JSON.stringify(exp), 
             function(err){
                if (err) throw err;
                console.log('The data was appended to file!');
              });

        })

    });

我的目标是,每个新添加的项目都应该附加到我的 JSON 文件中。 最后它应该如下所示:

 {"expArray": [{"id":0,"value":"200","date":"dqwd","tags":"cnelw"},
          {"id":1,"value":"300","date":"dqwd","tags":"ncjlekw"},
          {"id":2,"value":"22","date":"dqwd","tags":"dnkqoe"}

  ]}  

我不知道是否有必要在那里做一个数组? 但是我需要再次读取文件以备将来使用并获取项目的 ID 以在客户端删除它们或编辑它们。

感谢您的帮助!

【问题讨论】:

    标签: node.js json express socket.io handlebars.js


    【解决方案1】:

    试试这个:

    client.on('message', function(value, date, descr, tags) {
            console.log('message: ' + value, date, descr, tags );
    
            // exp object
            var exp = {id:id,value:value,date:date,tags:tags}
    
            expArr[exp.id] = exp;
            id++;
            console.log(exp.id);
    
    
    
            fs.readFile('expenses.json', function (err, data) {
                 var json = JSON.parse(data);
                 //      _------- add expArray
                 json.expArray.push(exp);
                 console.log(json);
                 fs.writeFile("expenses.json", JSON.stringify(exp), 
                 function(err){
                    if (err) throw err;
                    console.log('The data was appended to file!');
                  });
    
            })
    
        });
    

    【讨论】:

    • 谢谢!它可以工作,但是当您编写文件时,您需要对 json 进行字符串化,而不是 exp ( fs.writeFile("expenses.json", JSON.stringify(json) ) 。否则它将覆盖所有内容并只在JSON文件
    • 抱歉,有点疏忽 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    相关资源
    最近更新 更多