Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

writing js objects to files (including methods) in nodejs?

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?

Problem courtesy of: luisgo

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))
Solution courtesy of: Trevor

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

writing js objects to files (including methods) in nodejs?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×