All files / libs/storage FileStorage.js

100% Statements 29/29
100% Branches 12/12
100% Functions 8/8
100% Lines 27/27
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                    1x 1x   1x   4x 4x 4x   3x 3x 2x 1x 1x   1x     1x 1x             6x 5x 5x   4x 3x 3x   1x             2x 2x 2x 2x 1x           4x      
/**
 * 文件缓存
 *
 * @module      libs/storage/FileStorage
 * @createdAt   2016-07-21
 *
 * @copyright   Copyright (c) 2016 Zhonglei Qiu
 * @license     Licensed under the MIT license.
 */
 
var Storage = require('./Storage')
var fs = require('fs')
 
module.exports = Storage.extend({
  init: function(data) {
    var self = this
    return new Promise(function(resolve, reject) {
      if (self.data) return resolve()
 
      fs.readFile(self.opts.file, function(err, content) {
        if (err) {
          if (err.code === 'ENOENT') {
            self.data = Object(data)
            return self.update().then(resolve, reject)
          } else {
            return reject(err)
          }
        } else {
          self.data = JSON.parse(content.toString().trim())
          resolve()
        }
      })
    })
  },
 
  initSync: function(data) {
    if (!this.data) {
      try {
        this.data = JSON.parse(fs.readFileSync(this.opts.file).toString().trim())
      } catch (e) {
        if (e.code === 'ENOENT') {
          this.data = Object(data)
          this.updateSync()
        } else {
          throw e
        }
      }
    }
  },
 
  update: function() {
    var self = this
    return new Promise(function(resolve, reject) {
      fs.writeFile(self.opts.file, self.toString(), function(err) {
        if (err) return reject(err)
        resolve()
      })
    })
  },
 
  updateSync: function() {
    fs.writeFileSync(this.opts.file, this.toString())
  }
})