I'm running a Node server and I was wondering - how can I serialize objects and write them to a file?
-
1You might want a DB instead, e.g. Couch, Mongo, MySQL.mahemoff– mahemoff2011-09-02 14:51:46 +00:00Commented Sep 2, 2011 at 14:51
-
Do you want to write a string (or bytes) to a file or do you want to save any object?svick– svick2011-09-02 16:44:42 +00:00Commented Sep 2, 2011 at 16:44
-
1The question marked as duplicate is not asking the same thing. This question is really about serialization and writing to a file, not just writing to a file!corazza– corazza2014-03-14 11:22:08 +00:00Commented Mar 14, 2014 at 11:22
-
You edited your post; the original was not clear that you also meant serialization. In any case, it is still a duplicate; just of a different question, this time.Andrew Barber– Andrew Barber2014-03-26 02:03:06 +00:00Commented Mar 26, 2014 at 2:03
-
I looked at the question and it's younger than this one (asked in 2012)! Besides, the title is virtually the same as my own original title from 2011. Also it is asking a different thing, and the accepted answer is different as well. If I were to discover my question looking for serialization techniques I'd be confused.corazza– corazza2014-03-26 09:37:13 +00:00Commented Mar 26, 2014 at 9:37
|
Show 2 more comments
1 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: http://nodejs.org/docs/v0.4.11/api/fs.html#fs.write
3 Comments
Paul
you can also read-and-parse in one step by requiring a json file. e.g. var p = require('savefile.json');
Paul Verschoor
But this doesn't serialise any functions of the object.
Tony Topper
I thought it was more proper for the answer to contain the solution rather than link to a solution.