fs.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. const fss = require('fs');
  2. const fs = fss.promises;
  3. const path = require('path');
  4. const mkdirp = require('mkdirp');
  5. class FSStorage {
  6. constructor(config, log) {
  7. this.log = log;
  8. this.dir = config.file_dir;
  9. mkdirp.sync(this.dir);
  10. }
  11. async length(id) {
  12. const result = await fs.stat(path.join(this.dir, id));
  13. return result.size;
  14. }
  15. getStream(id) {
  16. return fss.createReadStream(path.join(this.dir, id));
  17. }
  18. set(id, file) {
  19. return new Promise((resolve, reject) => {
  20. const filepath = path.join(this.dir, id);
  21. const fstream = fss.createWriteStream(filepath);
  22. file.pipe(fstream);
  23. file.on('error', err => {
  24. fstream.destroy(err);
  25. });
  26. fstream.on('error', err => {
  27. this.del(id);
  28. reject(err);
  29. });
  30. fstream.on('finish', resolve);
  31. });
  32. }
  33. async del(id) {
  34. try {
  35. await fs.unlink(path.join(this.dir, id));
  36. } catch (e) {
  37. // ignore local fs issues
  38. }
  39. }
  40. ping() {
  41. return Promise.resolve();
  42. }
  43. }
  44. module.exports = FSStorage;