Javascript 如何将对象保存到 Node.js 中的文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7284849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:37:57  来源:igfitidea点击:

How can I save objects to files in Node.js?

javascripthtmlnode.js

提问by corazza

I'm running a Node server and I was wondering - how can I serialize objects and write them to a file?

我正在运行 Node 服务器,我想知道 - 如何序列化对象并将它们写入文件?

回答by ConfusedNoob

You can use

您可以使用

var str = JSON.stringify(object)

to serialize your objects to a JSON string and

将您的对象序列化为 JSON 字符串并

var obj = JSON.parse(string)

To read it back as an object. The string can be written to file. So, for example an object like this:

将其作为对象读回。字符串可以写入文件。因此,例如这样的对象:

var p = new Foo();
p.Bar = "Terry"
var s = JSON.stringify(p)
// write s to file, get => { "Bar" : "Terry" }
// read s from file and turn back into an object:
var p = JSON.parse(s);

Writing and reading to/from files is covered here: http://nodejs.org/docs/v0.4.11/api/fs.html#fs.write

此处介绍了对文件的写入和读取:http: //nodejs.org/docs/v0.4.11/api/fs.html#fs.write