javascriptnode.jsjsonwritefile

How to write and read an array of objects to a file


I have this array of objects:

var people = {name:'list 1',mode:0,friends:[{user:1,code:'red'},{user:2,code:'blue'}]};

I want to write it to a file so if the node server crashes I dont lose the data. I did this:

//define variables from file
var file = "../../people.txt";
var open = fs.readFileSync(file);
va data = open.toString();
var name = data.name;
var mode = data.mode;
var friends = data.friends;

whenever a variable changes I save it to a file like this:

function update() {
 //dosomething
 name = 'new list';
 mode = 1;
 friends = [{user:4,code:'red'},{user:6,code:'blue'}]

fs.writeFileSync(file,`{name:'${name}',mode:${mode},friends:${friends}'}`,{encoding:'utf8',flag:'w'});
}

This is output onto the file

{name:'list 1',mode:0,friends:[object, object]}

and the data cant be read at all. What am I supposed to do here?

Thank you.


Solution

  • You should convert the JSON data into a string format using JSON.stringify() before writing it to a file, and when reading them out, you should parse the string into JSON using JSON.parse()

    More details are here and how to read/write JSON files