FileSync.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. 'use strict';
  2. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  3. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  5. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  6. var fs = require('graceful-fs');
  7. var Base = require('./Base');
  8. var readFile = fs.readFileSync;
  9. var writeFile = fs.writeFileSync;
  10. // Same code as in FileAsync, minus `await`
  11. var FileSync = function (_Base) {
  12. _inherits(FileSync, _Base);
  13. function FileSync() {
  14. _classCallCheck(this, FileSync);
  15. return _possibleConstructorReturn(this, (FileSync.__proto__ || Object.getPrototypeOf(FileSync)).apply(this, arguments));
  16. }
  17. _createClass(FileSync, [{
  18. key: 'read',
  19. value: function read() {
  20. // fs.exists is deprecated but not fs.existsSync
  21. if (fs.existsSync(this.source)) {
  22. // Read database
  23. try {
  24. var data = readFile(this.source, 'utf-8').trim();
  25. // Handle blank file
  26. return data ? this.deserialize(data) : this.defaultValue;
  27. } catch (e) {
  28. if (e instanceof SyntaxError) {
  29. e.message = `Malformed JSON in file: ${this.source}\n${e.message}`;
  30. }
  31. throw e;
  32. }
  33. } else {
  34. // Initialize
  35. writeFile(this.source, this.serialize(this.defaultValue));
  36. return this.defaultValue;
  37. }
  38. }
  39. }, {
  40. key: 'write',
  41. value: function write(data) {
  42. return writeFile(this.source, this.serialize(data));
  43. }
  44. }]);
  45. return FileSync;
  46. }(Base);
  47. module.exports = FileSync;