dl
Version:
DreamLab Libs
169 lines (140 loc) • 4.96 kB
JavaScript
var fs = require('fs');
var Core = require('core'),
Class = Core.Class,
Assertions = Core.common.Assertions,
Types = Core.common.Types;
var AbstractDataProvider = require('./AbstractDataProvider.js').AbstractDataProvider;
var FileListProvider = function () {
this.Extends = AbstractDataProvider;
this.initialize = function (fileList) {
Assertions.isArray(fileList, FileListProvider.Exception.BAD_FILE_NAME);
this._fileList = fileList;
};
this._merge = function (data) {
if (data.length < 2) {
return data;
}
var i = 1,
length = data.length,
key,
tmp = data[0];
for (; i < length; i++) {
for (key in data[i]) {
if (data[i].hasOwnProperty(key)) {
tmp[key] = data[i][key];
}
}
}
return tmp;
};
this.init = function (callback) {
var that = this,
i = 0,
length = this._fileList.length,
tmp = length,
error = {};
success = function () {
if (--tmp == 0) {
var keys = Object.keys(error);
if (keys.length) {
callback(error, null);
} else {
callback(null, true);
}
}
};
for (; i < length; i++) {
fs.stat(this._fileList[i], function (file) {
return function (err, stats) {
if (err) {
if (err.code != "ENOENT") {
error[file] = err;
success();
return;
} else {
fs.writeFile(file, '', function (err) {
if (err) {
error[file] = err;
success()
return;
}
success();
});
}
return;
}
success();
};
}(this._fileList[i]));
}
};
this.destroy = function () {
this.unwatch(null, function () {});
};
this.watch = function (key, callback) {
var i = 0, length = this._fileList.length;
for(; i < length; i++) {
fs.watchFile(this._fileList[i], function (current, previous) {
if (current.size == 0) {
/*
* pomijam event przy czyszczeniu pliku
* po CLOSE_WRITE zostanie wygenerowany nowy event
*/
} else {
callback(null, current);
}
});
}
};
this.unwatch = function (key, callback) {
var i = 0, length = this._fileList.length;
for(; i < length; i++) {
fs.unwatchFile(this._fileList[i]);
}
callback();
};
this.set = function (key, value, callback) {
throw FileListProvider.Exception.SET_NOT_SUPPORTED;
};
this.get = function (key, callback) {
var that = this,
data = [],
error = {},
i = 0,
length = this._fileList.length,
tmp = length,
success = function () {
if (--tmp == 0) {
var keys = Object.keys(error);
if (keys.length) {
callback(error, null);
} else {
callback(null, that._merge(data));
}
}
};
for (; i < length; i++) {
fs.readFile(this._fileList[i], 'utf8', function (index, file) {
return function (err, d) {
if (err) {
error[file] = err;
success();
return;
}
try {
d = JSON.parse(d);
} catch (e) {
d = {};
}
data[index] = d;
success();
};
}(i, this._fileList[i]));
}
};
};
FileListProvider = new Class(new FileListProvider());
FileListProvider.Exception = {};
FileListProvider.Exception.BAD_FILE_NAME = "Array of files has to be passed";
FileListProvider.Exception.SET_NOT_SUPPORTED = "Setting configuration is not supported";
exports.FileListProvider = FileListProvider;