我看到了如何按照这里描述的方式将对象写入文件: 如何在Node.js中将对象保存到文件中? 但是否有一种方法可以将对象写成一种方式,使我能够重新加载该对象到内存中,包括其方法?
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();
}
这个方法可以处理大多数类型的数据,但总有一些奇怪的情况会破坏它,因此我不建议在生产环境中使用。反序列化的方法如下:
eval('var test = ' + dump_to_string(obj))
toJSON
方法以自定义对象的序列化,例如<SomeObject>.prototype.toJSON
。为了更灵活,可以定义一个替换器(replacer)用于JSON.stringify
。 - Rob Wobj.replace
应该使用 /"/g
来确保所有的 "
都被正确替换,而不仅仅是第一个。 - Chris Houghtonfs = require 'fs'
bson = require('bson').BSONPure.BSON
obj = {
string: "test",
func: (s) ->
console.log s
}
fs.writeFile 'test.txt', bson.serialize(obj, false, false, true), (err) ->
return console.log("Err : #{err}") if err
fs.readFile 'test.txt', (err, file) ->
return console.log("Err : #{err}") if err
deserialized = bson.deserialize file, evalFunctions: true
deserialized.func deserialized.string // Outputs 'text', as expected
我最近编写了shoveJS: https://shovemedia.github.io/shovejs/ 来处理这种情况。YMMV -- 我还没有尝试过在Node中使用它。
它将一个类型化的对象结构转换为JSON(然后您可以将其保存到磁盘上),并且可以将该结构膨胀回包括正确的对象->对象引用等在内的类型化对象。需要明确的是,方法/类定义本身不会被序列化。系统只是期望在序列化期间可用的已注册的Model / Factory类也在反序列化期间可用。
提前道歉,我没有发布一些简单的示例。
编辑:该技术是Rob W在下面评论中提到的升级版。
eval
函数。 - freakish