I'm running a Node server and I was wondering - how can I serialize objects and write them to a file?
Object. defineProperty(Object. prototype, 'clone', { enumerable: false, value: function() { var newObj = (this instanceof Array) ? [] : {}; for (i in this) { if (i == 'clone') continue; if (this[i] && typeof this[i] == "object") { newObj[i] = this[i].
copyFile() method is used to asynchronously copy a file from the source path to destination path. By default, Node. js will overwrite the file if it already exists at the given destination. The optional mode parameter can be used to modify the behavior of the copy operation.
writeFile("/tmp/test", message, function (err) { if (err) { return console. log(err); } console. log("The file was saved!"); }); }); Hope this works for you.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With