我想将对象(带方法)存储到文件或数据库中。例如
var fs = require('fs');
function Worker(name, age){
this.name = name;
this.age = age;
}
Worker.prototype.work = function(){
console.log("I am working...");
}
worker = new Worker("Alice", 20);
worker.work();
fs.writeFile(
"worker.json",
JSON.stringify(worker),
function(){}
);
当我读取JSON文件时,我可以加载" work()"方法:
fs.readFile("worker.json", function(err, data) {
worker = JSON.parse(data);
worker.work(); // I am working...
}
我怎样才能做到这一点?