2

I'm trying to push names in a json file. I'm trying to do something like:

socket.on('create json', function(data){
    var data = JSON.stringify(Data, null, 2);
    fs.writeFile('participants.json', data)
    console.log(data);
});

This is only outputting the data that I've send and results in:

{
  "type": "Buffer",
  "data": [34,69,120,97,109,112,108,101,32,110,97,109,101, 34 ]
}

When I'm writing the file it deletes everything and puts that in. I'm looking for a way to write:

{
"names":["name1", "name2", "name3"]
}

Any ideas on how to fix and write this?

Help is very much appreciated!

4
  • 3
    i still cant understand your problem, read (5 times) go for read another 5 times Commented Oct 17, 2017 at 10:12
  • 2
    Is it just a bad example or do you really have data as a parameter, data as a variable and Data? Commented Oct 17, 2017 at 10:12
  • not sure, may be you want to append the data in the existing file , open the file in append mode, refer stackoverflow.com/questions/33418777/… Commented Oct 17, 2017 at 10:17
  • I'm just asking for a way to write a json file without getting the whole file deleted that's all basically Commented Oct 17, 2017 at 10:52

1 Answer 1

1

you have to again read your file, parse the JSON, append your new result to the array, transform it back into a string and save it again.

var fs = require('fs')

fs.readFile('participants.json', function (err, data) {
    var json = JSON.parse(data);
    json.name = ["name1", "name2", "name3"];
    fs.writeFile("results.json", JSON.stringify(json))
})
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks bro this worked for me! now i'll figure out how to get an name from an input field in there! Thanks you so much!
Can you help me to get values into the array? I get the values from an input field. Sorry im new to JS :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.