SerializerJson.js 909 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. const fs = require('graceful-fs');
  2. const promisify = require('./util/promisify');
  3. const fsReadFile = promisify(fs.readFile, { context: fs });
  4. const fsWriteFile = promisify(fs.writeFile, { context: fs });
  5. class JsonSerializer {
  6. constructor({ cacheDirPath }) {
  7. this.path = cacheDirPath;
  8. if (!/\.json$/.test(this.path)) {
  9. this.path += '.json';
  10. }
  11. }
  12. read() {
  13. const cacheDirPath = this.path;
  14. return fsReadFile(cacheDirPath, 'utf8')
  15. .catch(() => '{}')
  16. .then(JSON.parse);
  17. }
  18. write(moduleOps) {
  19. const cacheDirPath = this.path;
  20. return this.read()
  21. .then(cache => {
  22. for (let i = 0; i < moduleOps.length; i++) {
  23. const op = moduleOps[i];
  24. cache[op.key] = op.value;
  25. }
  26. return cache;
  27. })
  28. .then(JSON.stringify)
  29. .then(cache => fsWriteFile(cacheDirPath, cache));
  30. }
  31. }
  32. module.exports = JsonSerializer;