SerializerFile.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. const fs = require('graceful-fs');
  2. const join = require('path').join;
  3. const _mkdirp = require('mkdirp');
  4. const promisify = require('./util/promisify');
  5. const mkdirp = promisify(_mkdirp);
  6. const fsReadFile = promisify(fs.readFile, { context: fs });
  7. const fsReaddir = promisify(fs.readdir, { context: fs });
  8. const fsWriteFile = promisify(fs.writeFile, { context: fs });
  9. class FileSerializer {
  10. constructor({ cacheDirPath }) {
  11. this.path = cacheDirPath;
  12. }
  13. read() {
  14. const assets = {};
  15. const cacheAssetDirPath = this.path;
  16. return mkdirp(cacheAssetDirPath)
  17. .then(() => fsReaddir(cacheAssetDirPath))
  18. .then(dir =>
  19. dir.map(name =>
  20. Promise.all([name, fsReadFile(join(cacheAssetDirPath, name))]),
  21. ),
  22. )
  23. .then(a => Promise.all(a))
  24. .then(_assets => {
  25. for (let i = 0; i < _assets.length; i++) {
  26. assets[_assets[i][0]] = _assets[i][1];
  27. }
  28. })
  29. .then(() => assets);
  30. }
  31. write(assetOps) {
  32. const cacheAssetDirPath = this.path;
  33. return mkdirp(cacheAssetDirPath)
  34. .then(() =>
  35. assetOps.map(({ key, value }) => {
  36. const assetPath = join(cacheAssetDirPath, key);
  37. return fsWriteFile(assetPath, value);
  38. }),
  39. )
  40. .then(a => Promise.all(a));
  41. }
  42. }
  43. module.exports = FileSerializer;