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


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

3/26/2014 2:02:20 AM

Accepted Answer

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:

9/2/2011 4:07:29 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow