简体   繁体   English

如何将对象数组写入和读取文件

[英]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'}]}; 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这是文件中的 output

{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()您应该在将 JSON 数据转换为字符串格式之前使用JSON.stringify()将其写入文件,并且在读取它们时,您应该使用 JSON 将字符串解析为JSON.parse()

More details are here and how to read/write JSON files更多细节在这里以及如何读/写 JSON 文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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