开发者

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

开发者 https://www.devze.com 2023-04-02 15:25 出处:网络
This question already has answers here: writing js objects 开发者_高级运维to files (including methods) in nodejs?
This question already has answers here: writing js objects 开发者_高级运维to files (including methods) in nodejs? (3 answers) Closed 9 years ago.

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


You can use

var str = JSON.stringify(object)

to serialize your objects to a JSON string and

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

0

精彩评论

暂无评论...
验证码 换一张
取 消