MCSManager/core/DataModel.js

62 lines
1.4 KiB
JavaScript
Raw Normal View History

2020-10-08 11:59:48 +08:00
let fs = require("fs");
const EventEmitter = require("events");
2017-11-13 12:26:31 +08:00
class DataModel {
2020-10-08 11:59:48 +08:00
constructor(filename) {
this.__filename__ = "./" + filename + ".json";
}
filename(newFilename) {
if (newFilename) this.__filename__ = newFilename + ".json";
else return this.__filename__;
}
load() {
// 同步而非异步 因为我们必须要线性执行而且读取的文件很小
let data = fs.readFileSync(this.__filename__, "utf-8");
let ele = JSON.parse(data);
for (var key in ele) {
this[key] = ele[key];
2017-11-13 12:26:31 +08:00
}
2020-10-08 11:59:48 +08:00
}
save() {
let name = this.__filename__;
// 同步而非异步 因为我们必须要线性执行而且读取的文件很小
fs.writeFileSync(this.__filename__, JSON.stringify(this, null, 4));
}
isExist(callback) {
fs.exists(this.filename, function (exists) {
callback(exists);
});
}
update(needJson) {
for (let key in needJson) {
this[key] = needJson[key];
2017-11-13 12:26:31 +08:00
}
2020-10-08 11:59:48 +08:00
}
upload(that, needkey) {
let key = null;
if (needkey == undefined) {
for (var mineKey in this) {
that[key] = this[key];
}
return;
2017-11-13 12:26:31 +08:00
}
2020-10-08 11:59:48 +08:00
for (let i = 0; i < needkey.length; i++) {
key = needkey[i];
if (this.hasOwnProperty(key)) {
that[key] = this[key];
} else {
that[key] = undefined;
}
2017-11-13 12:26:31 +08:00
}
2020-10-08 11:59:48 +08:00
return;
}
2017-11-13 12:26:31 +08:00
}
2020-10-08 11:59:48 +08:00
module.exports = DataModel;