s3.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. const AWS = require('aws-sdk');
  2. class S3Storage {
  3. constructor(config, log) {
  4. this.bucket = config.s3_bucket;
  5. this.log = log;
  6. const cfg = {};
  7. if (config.s3_endpoint != '') {
  8. cfg['endpoint'] = config.s3_endpoint;
  9. }
  10. cfg['s3ForcePathStyle'] = config.s3_use_path_style_endpoint;
  11. AWS.config.update(cfg);
  12. this.s3 = new AWS.S3();
  13. }
  14. async length(id) {
  15. const result = await this.s3
  16. .headObject({ Bucket: this.bucket, Key: id })
  17. .promise();
  18. return Number(result.ContentLength);
  19. }
  20. getStream(id) {
  21. return this.s3
  22. .getObject({ Bucket: this.bucket, Key: id })
  23. .createReadStream();
  24. }
  25. set(id, file) {
  26. const upload = this.s3.upload({
  27. Bucket: this.bucket,
  28. Key: id,
  29. Body: file
  30. });
  31. file.on('error', () => upload.abort());
  32. return upload.promise();
  33. }
  34. del(id) {
  35. return this.s3.deleteObject({ Bucket: this.bucket, Key: id }).promise();
  36. }
  37. ping() {
  38. return this.s3.headBucket({ Bucket: this.bucket }).promise();
  39. }
  40. }
  41. module.exports = S3Storage;