简体   繁体   中英

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.

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

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