15815213711
2024-08-26 67b8b6731811983447e053d4396b3708c14dfe3c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const Base = require('./Base')
const fs = require('fs')
const Log = require('../../../log')
 
class FileSync extends Base {
 
  constructor(options = {}) {
    const { source,  isSysDB } = options;
    super(source);
    this.isSysDB = isSysDB;
  }
  
  read() {
    if (fs.existsSync(this.source)) {
      // Read database
      let data = fs.readFileSync(this.source, {encoding: 'utf8'}).trim();
 
      // 是否可以正常解析
      let canDeserialized = this._canDeserialized(data);
      if (!canDeserialized) {
        let errMessage = `[ee-core] [storage/jsondb] malformed json in file: ${this.source}\n${data}`;
        Log.coreLogger.error(errMessage);
 
        // 是否文件结尾多一个括号,尝试处理
        data = data.trim().slice(0, -1);
        canDeserialized = this._canDeserialized(data);
        if (canDeserialized) {
          // 转换为对象,并写入
          const newData = JSON.parse(data);
          this._fsWrite(newData);
        } else {
          //  [todo] 重置 system.json ,不处理用户数据
          if (this.isSysDB) {
            this._fsWrite(this.defaultValue);
          }
          errMessage = '[ee-core] [storage/jsondb] malformed json that cannot be handled!';
          Log.coreLogger.error(errMessage);
        }
      }
      const value = canDeserialized ? this.deserialize(data) : this.defaultValue;
      return value;
    } else {
      // Initialize
      this._fsWrite(this.defaultValue);
      return this.defaultValue
    }
  }
 
  write(data) {
    return this._fsWrite(data);
  }
 
  _fsWrite(data) {
    const isObject = Object.prototype.toString.call(data) === '[object Object]';
    if (!isObject) {
      Log.coreLogger.error('[ee-core] [storage/jsondb] Variable is not an object :', data);
      return
    }
 
    return fs.writeFileSync(this.source, this.serialize(data), {flag:'w+'})
  }
}
 
module.exports = FileSync