From 4c4d55f541d96b41dde772c84cb34583c800dca9 Mon Sep 17 00:00:00 2001 From: Louis Chatriot Date: Wed, 1 May 2013 20:23:24 +0100 Subject: [PATCH] Able to load and understand a database --- lib/datastore.js | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) 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); });