FileStore.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. const Store = require('./Store');
  2. const isEmpty = require('./isEmpty');
  3. const debounce = require('./debounce');
  4. const stringify = require('./stringify');
  5. const isObj = require('./isObj');
  6. const defaults = require('./defaults');
  7. const noop = require('./noop');
  8. const fs = require('fs');
  9. exports = Store.extend({
  10. initialize: function FileStore(path, data) {
  11. this._path = path;
  12. data = data || {};
  13. let fileData;
  14. if (fs.existsSync(path)) {
  15. try {
  16. fileData = JSON.parse(fs.readFileSync(path, 'utf8'));
  17. } catch (e) {
  18. fileData = {};
  19. }
  20. }
  21. if (!isObj(fileData)) {
  22. fileData = {};
  23. }
  24. data = defaults(fileData, data);
  25. this.save = debounce(data => {
  26. if (isEmpty(data)) {
  27. fs.unlink(this._path, noop);
  28. return;
  29. }
  30. fs.writeFile(this._path, stringify(data), 'utf8', noop);
  31. }, 300);
  32. this.callSuper(Store, 'initialize', [data]);
  33. }
  34. });
  35. module.exports = exports;