Saving JSON data correctly on nodeJS server

时间:2019-02-02 13:22:14

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

I'm still working on my SPA where can I track my expenses. Each Expense Item consists of a value, a date , description and tags.

The client send all these data to my server , where I want to save it in a JSON file.

My code looks like this right now: (json.push isnt working)

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

        })

    });

My goal is, every newly added item should append to my JSON file. In the end it should look like this for example:

 {"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"}

  ]}  

I dont know if it's necessary to to do an array there? But I need to read the file again for the future and get the ID of the items to delete them on client-side or edit them.

Thanks for ur help!

1 个答案:

答案 0 :(得分:1)

尝试一下:

netstat -an | find ":5000"