Refactor LogWriter history

This commit is contained in:
Guillaume Wuip 2014-10-30 19:15:04 +01:00
parent 0bf1253717
commit 7f706c5aa4

View file

@ -39,13 +39,26 @@
} }
//Init history //Init history
this.initHistory();
};
/**
* LogWriter.prototype.initHistory
*
* Attach and init the history property
*/
LogWriter.prototype.initHistory = function () {
this.history = { this.history = {
dates : {} dates : {}
}; };
var historyPath = path.join(this.rootPath, 'history.json');
if (!fs.existsSync(historyPath)) { //create file if doesn't exist yet
this.writeFile( this.writeFile(
path.join(this.rootPath, 'history.json'), historyPath,
this.history, this.history,
function (err) { function (err) {
if (err) { if (err) {
@ -53,6 +66,25 @@
} }
} }
); );
} 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); callback(err);
} else { } else {
var newFile = fs.existsSync(pathToFile); var newFile = !fs.existsSync(pathToFile);
fs.appendFile(pathToFile, content, function (err) { fs.appendFile(pathToFile, content, function (err) {
@ -140,14 +172,6 @@
var historyPath = path.join(this.rootPath, 'history.json'), var historyPath = path.join(this.rootPath, 'history.json'),
self = this; self = this;
fs.readFile(
historyPath,
function (err, data) {
if (err) {
throw err;
} else {
try {
var today = moment().startOf('day').valueOf().toString(); var today = moment().startOf('day').valueOf().toString();
//Save the path under today key //Save the path under today key
@ -156,6 +180,8 @@
self.history.dates[today] = []; self.history.dates[today] = [];
} }
if (self.history.dates[today].indexOf(pathToFile) === -1) {
self.history.dates[today].push(pathToFile); self.history.dates[today].push(pathToFile);
self.writeFile(historyPath, self.history, function (err) { self.writeFile(historyPath, self.history, function (err) {
@ -163,15 +189,8 @@
throw err; throw err;
} }
}); });
} catch (e) {
throw e;
} }
}
}
);
}; };
/** /**