diff --git a/lib/datastore.js b/lib/datastore.js index 5e7b414..d569702 100644 --- a/lib/datastore.js +++ b/lib/datastore.js @@ -34,9 +34,9 @@ Datastore.prototype.loadDatabase = function (cb) { self.data = []; fs.writeFile(self.filename, '', 'utf8', function (err) { return callback(err); }); } else { - fs.readFile(self.filename, 'utf8', function (err, data) { + fs.readFile(self.filename, 'utf8', function (err, rawData) { if (err) { return callback(err); } - self.data = data; + self.data = Datastore.treatRawData(rawData); return callback(); }); } @@ -45,14 +45,31 @@ Datastore.prototype.loadDatabase = function (cb) { }; +/** + * From a database's raw data, return the corresponding + * machine understandable collection + */ +Datastore.treatRawData = function (rawData) { + var data = rawData.split('\n') + , res = []; + + data.forEach(function (d) { + var doc; + + try { + doc = JSON.parse(d); + res.push(doc); + } catch (e) { + } + }); + + return res; +}; var d = new Datastore('workspace/test.db'); d.loadDatabase(function (err) { - console.log("===="); - console.log(err); - console.log(d.data); });