将js对象写入nodejs中的文件(包括方法)?

lui*_*sgo 7 javascript node.js

我看到如何将对象写入文件,如下所述:如何将对象保存到Node.js中的文件?但是有没有办法获取一个对象并以允许我将对象重新加载到内存中的方式编写它,包括它的方法?

Tre*_*vor 6

正如@AnthonySottile之前说的那样,这可能是非常危险的,我不确定它是否有一个很好的用例,但只是为了踢和咯咯,你需要编写自己的递归序列化器.像这样的东西:

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<len; i++) {
        buff.push(dump_to_string(arr[i]));
    }
    return '[' + buff.join(', ') + ']';
}

function dump_to_string(obj) {
    if (toString.call(obj) == '[object Function]') {
        return obj.toString();
    } else if (toString.call(obj) == '[object Array]') {
        return dump_array(obj);
    } else if (toString.call(obj) == '[object String]') {
        return '"' + obj.replace('"', '\\"') + '"';
    } else if (obj === Object(obj)) {
        return dump_object(obj);
    }
    return obj.toString();
}
Run Code Online (Sandbox Code Playgroud)

这将处理大多数类型,但总有一个奇怪的球混乱它的机会所以我不会在生产中使用它.之后反序列化就像下面这样简单:

eval('var test = ' + dump_to_string(obj))
Run Code Online (Sandbox Code Playgroud)

  • O_O你为什么要重新发明轮子?定义用于对象的自定义序列化的`toJSON`方法,例如.`<SomeObject> .prototype.toJSON`.为了更加灵活,请定义[JSON.stringify`的替换器](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify#Syntax). (3认同)