storage-folder.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. const path = require('path');
  2. const fs = require('fs-plus');
  3. module.exports = class StorageFolder {
  4. constructor(containingPath) {
  5. if (containingPath) {
  6. this.path = path.join(containingPath, 'storage');
  7. }
  8. }
  9. store(name, object) {
  10. return new Promise((resolve, reject) => {
  11. if (!this.path) return resolve();
  12. fs.writeFile(
  13. this.pathForKey(name),
  14. JSON.stringify(object),
  15. 'utf8',
  16. error => (error ? reject(error) : resolve())
  17. );
  18. });
  19. }
  20. load(name) {
  21. return new Promise(resolve => {
  22. if (!this.path) return resolve(null);
  23. const statePath = this.pathForKey(name);
  24. fs.readFile(statePath, 'utf8', (error, stateString) => {
  25. if (error && error.code !== 'ENOENT') {
  26. console.warn(
  27. `Error reading state file: ${statePath}`,
  28. error.stack,
  29. error
  30. );
  31. }
  32. if (!stateString) return resolve(null);
  33. try {
  34. resolve(JSON.parse(stateString));
  35. } catch (error) {
  36. console.warn(
  37. `Error parsing state file: ${statePath}`,
  38. error.stack,
  39. error
  40. );
  41. resolve(null);
  42. }
  43. });
  44. });
  45. }
  46. pathForKey(name) {
  47. return path.join(this.getPath(), name);
  48. }
  49. getPath() {
  50. return this.path;
  51. }
  52. };