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!

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
Sylent
  • 474
  • 1
  • 9
  • 25
  • 3
    i still cant understand your problem, read (5 times) go for read another 5 times – Álvaro Touzón Oct 17 '17 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`? – Daniel Hilgarth Oct 17 '17 at 10:12
  • not sure, may be you want to append the data in the existing file , open the file in append mode, refer https://stackoverflow.com/questions/33418777/node-js-write-a-line-into-a-txt-file – LogicBlower Oct 17 '17 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 – Sylent Oct 17 '17 at 10:52

1 Answers1

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))
})
  • 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! – Sylent Oct 17 '17 at 11:08
  • Can you help me to get values into the array? I get the values from an input field. Sorry im new to JS :) – Sylent Oct 17 '17 at 11:29