简体   繁体   中英

How to write key + values to a JSON file with Node.js and Socket.io

I am working on a scoreboard with Socket.io and Node.js . Now I would like to save the scores of the participants into a JSON file.

This is what I tried to do:

socket.on('part score', function(name, score){
    let jdata = fs.readFileSync('participants.json');
    let json = JSON.parse(jdata);
console.log(name, score);
//outputs: foo 10

    fs.writeFile('participants.json', JSON.stringify(json.jury1.push({name: score}, null, 2)), function(){
        console.log("name added: "+name+" value added: "+score);
    }); 
});

How my JSON file looks like:

{"jury1": []}

When I executed to code above my JSON files turns into "3" when the score is 10. Also everything in my JSON file is gone after execution.

How do I properly add the key+value into my Jury1? Thanks already!
ps: name and score gets send through the client sided script

Jury1 is an array?

I think that you should parse all the data that you want so instead of doing:

JSON.stringify(json.jury1.push({name: score}, null, 2)

try something like:

jury1 with the score you need var data = JSON.stringify(jury1)

You already have a json file. Why are you doing a JSON.parse again ? I suspect that is the issue. can you try to print the content of json.jury1 to confirm the same ?

Also, check the result from fs.writeFile() if there is any err

fs.writeFile('participants.json', JSON.stringify(json.jury1.push({name: score}, null, 2)), function(err){
    console.log(err, "name added: "+name+" value added: "+score);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM