s3.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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.getObject({ Bucket: this.bucket, Key: id }).createReadStream();
  22. }
  23. set(id, file) {
  24. const upload = this.s3.upload({
  25. Bucket: this.bucket,
  26. Key: id,
  27. Body: file
  28. });
  29. file.on('error', () => upload.abort());
  30. return upload.promise();
  31. }
  32. del(id) {
  33. return this.s3.deleteObject({ Bucket: this.bucket, Key: id }).promise();
  34. }
  35. ping() {
  36. return this.s3.headBucket({ Bucket: this.bucket }).promise();
  37. }
  38. }
  39. module.exports = S3Storage;