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,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;
}
}
}
);
});
}
};