writing js objects to files (including methods) in nodejs?
Problem
I see how I can write objects to files as described here: How can I save objects to files in Node.js? but is there a way to take an object and write it in a way that allows me to reload the object into memory including its methods?
Solution
As @AnthonySottile said before, this can be extremely dangerous and I'm not sure there is ever a good use case for it, but just for kicks and giggles you would need to write your own recursive serializer. Something like this:
var toString = Object.prototype.toString;
function dump_object(obj) {
var buff, prop;
buff = [];
for (prop in obj) {
buff.push(dump_to_string(prop) + ': ' + dump_to_string(obj[prop]))
}
return '{' + buff.join(', ') + '}';
}
function dump_array(arr) {
var buff, i, len;
buff = [];
for (i=0, len=arr.length; i
This will handle most types, but there is always the chance of an oddball messing it up so I would not use this in production. Afterwards unserializing is as easy as:
eval('var test = ' + dump_to_string(obj))
Discussion
View additional discussion.