File size: 1,788 Bytes
af5a34b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import fs from 'fs'
import YAML from 'yaml'
import _ from 'lodash'
import chokidar from 'chokidar'

export default class YamlReader {
  /**
   * 读写yaml文件
   *
   * @param yamlPath yaml文件绝对路径
   * @param isWatch 是否监听文件变化
   */
  constructor(yamlPath, isWatch = false) {
    this.yamlPath = yamlPath
    this.isWatch = isWatch
    this.initYaml()
  }

  initYaml() {
    // parseDocument 将会保留注释
    this.document = YAML.parseDocument(fs.readFileSync(this.yamlPath, 'utf8'))
    if (this.isWatch && !this.watcher) {
      this.watcher = chokidar.watch(this.yamlPath).on('change', () => {
        if (this.isSave) {
          this.isSave = false
          return
        }
        this.initYaml()
      })
    }
  }

  /** 返回读取的对象 */
  get jsonData() {
    if (!this.document) {
      return null
    }
    return this.document.toJSON()
  }

  /* 检查集合是否包含key的值 */
  has(keyPath) {
    return this.document.hasIn(keyPath.split('.'))
  }

  /* 返回key的值 */
  get(keyPath) {
    return _.get(this.jsonData, keyPath)
  }

  /* 修改某个key的值 */
  set(keyPath, value) {
    this.document.setIn([keyPath], value)
    this.save()
  }

  /* 删除key */
  delete(keyPath) {
    this.document.deleteIn(keyPath.split('.'))
    this.save()
  }

  // 数组添加数据
  addIn(keyPath, value) {
    this.document.addIn(keyPath.split('.'), value)
    this.save()
  }

  // 彻底删除某个key
  deleteKey(keyPath) {
    let keys = keyPath.split('.')
    keys = this.mapParentKeys(keys)
    this.document.deleteIn(keys)
    this.save()
  }

  // 保存yaml文件,写入文件
  save() {
    this.isSave = true
    let yaml = this.document.toString()
    fs.writeFileSync(this.yamlPath, yaml, 'utf8')
  }
}