在 nodeJS 服务器上正确保存 JSON 数据

Saving JSON data correctly on nodeJS server

我仍在处理我的 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 以在客户端删除它们或编辑它们。

感谢您的帮助!

试试这个:

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

        })

    });