1

I want to store objects (with methods) in to file or DB. For example

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(){}
);

When I read the JSON file I can load the "work()" method:

fs.readFile("worker.json", function(err, data) {
    worker = JSON.parse(data);
    worker.work(); // I am working...
}

How can I achieve this?

Jan Leo
  • 293
  • 1
  • 2
  • 6
  • possible duplicate of [Howt to serialize object in Javascript?](http://stackoverflow.com/questions/11759917/howt-to-serialize-object-in-javascript) – extols Aug 26 '14 at 11:35
  • You can't store methods in JSON, and it's impossible to retain closures in serialisation of functions. Rather have a look at the possible duplicate [Casting plain objects to function instances (“classes”) in javascript](http://stackoverflow.com/q/11810028/1048572) – Bergi Aug 26 '14 at 11:38
  • 1
    Setting aside the fact that's not possible (or at least not obvious how) to serialize a function's variable closure: from a performance perspective, why would you *want* to serialize prototype functions? Everything single serialized object would have extra bytes for a function that we know a `Worker` *always* has. Just construct a new `Worker` object at deserialization time, using the data (unique to that object) from the deserialized object and let the object inherit the prototype functions from `Worker.prototype`. – apsillers Aug 26 '14 at 12:20
  • @apsillers Thanks, but how to "let the object inherit the prototype functions from Worker.prototype". If Worker.prototype have many methods, is there some easier ways than worker.work = Worker.prototype.work. – Jan Leo Aug 26 '14 at 12:34
  • In between your middle two lines in your bottom code snippet: `var realWorker = new Worker(worker.name, worker.age);` for example. (And then use `realWorker.work()`.) A better solution is to modify the `Worker` constructor so it reads its properties from a single object; e.g., `new Worker({ name:"Alice", age: 20 })` as a call to `function Worker(obj) { this.age = obj.age; ... }` so you can simply call `realWorker = new Worker(worker)`. – apsillers Aug 26 '14 at 12:37
  • @apsillers Suppose that, Worker is in a library, so that I cannot modify its code. And suppose that Worker class is very complex (e.g. age is also an object with methods). – Jan Leo Aug 26 '14 at 12:43

0 Answers0