diff --git a/lib/logWriter.js b/lib/logWriter.js index ebdfff8..8b1f4e0 100644 --- a/lib/logWriter.js +++ b/lib/logWriter.js @@ -39,20 +39,52 @@ } //Init history + this.initHistory(); + }; + + /** + * LogWriter.prototype.initHistory + * + * Attach and init the history property + */ + LogWriter.prototype.initHistory = function () { this.history = { dates : {} }; - this.writeFile( - path.join(this.rootPath, 'history.json'), - this.history, - function (err) { + var historyPath = path.join(this.rootPath, 'history.json'); + + if (!fs.existsSync(historyPath)) { //create file if doesn't exist yet + + this.writeFile( + historyPath, + this.history, + function (err) { + if (err) { + throw err; + } + } + ); + + } else { //get history if file exists + + var self = this; + + fs.readFile(historyPath, function (err, data) { if (err) { throw err; + } else { + try { + + self.history = JSON.parse(data); + + } catch (e) { + throw e; + } } - } - ); + }); + } }; /** @@ -88,7 +120,7 @@ callback(err); } else { - var newFile = fs.existsSync(pathToFile); + var newFile = !fs.existsSync(pathToFile); fs.appendFile(pathToFile, content, function (err) { @@ -140,37 +172,24 @@ var historyPath = path.join(this.rootPath, 'history.json'), self = this; - fs.readFile( - historyPath, - function (err, data) { + var today = moment().startOf('day').valueOf().toString(); + + //Save the path under today key + + if (!self.history.dates[today]) { + self.history.dates[today] = []; + } + + if (self.history.dates[today].indexOf(pathToFile) === -1) { + + self.history.dates[today].push(pathToFile); + + self.writeFile(historyPath, self.history, function (err) { if (err) { throw err; - } else { - - try { - var today = moment().startOf('day').valueOf().toString(); - - //Save the path under today key - - if (!self.history.dates[today]) { - self.history.dates[today] = []; - } - - self.history.dates[today].push(pathToFile); - - self.writeFile(historyPath, self.history, function (err) { - if (err) { - throw err; - } - }); - - } catch (e) { - throw e; - } - } - } - ); + }); + } };