在nodejs中将js对象写入文件(包括方法)? [英] writing js objects to files (including methods) in nodejs?
问题描述
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?
推荐答案
正如@AnthonySottile之前说的那样,这可能非常危险,我不确定是否有很好的用例,只是用于踢球和傻笑.您将需要编写自己的递归序列化器.像这样:
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<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();
}
这将处理大多数类型,但是总是有一个奇怪的问题将其弄乱的机会,因此我不会在生产中使用它.然后,反序列化就像:
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))
这篇关于在nodejs中将js对象写入文件(包括方法)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!