租房小程序前端代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.7 KiB

3 months ago
  1. const fs = require('fs');
  2. const is = require('is-type-of');
  3. const { isObject } = require('../utils/isObject');
  4. const proto = exports;
  5. /**
  6. * get
  7. * @param {String} name - object name
  8. * @param {String | Stream | Object} file - file path or file stream or options
  9. * @param {Object} options
  10. * @param {{res}}
  11. */
  12. proto.get = async function get(name, file, options = {}) {
  13. let writeStream = null;
  14. let needDestroy = false;
  15. if (is.writableStream(file)) {
  16. writeStream = file;
  17. } else if (is.string(file)) {
  18. writeStream = fs.createWriteStream(file);
  19. needDestroy = true;
  20. } else if (isObject(file)) {
  21. // get(name, options)
  22. options = file;
  23. }
  24. options = options || {};
  25. const isBrowserEnv = process && process.browser;
  26. const responseCacheControl = options.responseCacheControl === null ? '' : 'no-cache';
  27. const defaultSubresOptions =
  28. isBrowserEnv && responseCacheControl ? { 'response-cache-control': responseCacheControl } : {};
  29. options.subres = Object.assign(defaultSubresOptions, options.subres);
  30. if (options.versionId) {
  31. options.subres.versionId = options.versionId;
  32. }
  33. if (options.process) {
  34. options.subres['x-oss-process'] = options.process;
  35. }
  36. let result;
  37. try {
  38. const params = this._objectRequestParams('GET', name, options);
  39. params.writeStream = writeStream;
  40. params.successStatuses = [200, 206, 304];
  41. result = await this.request(params);
  42. if (needDestroy) {
  43. writeStream.destroy();
  44. }
  45. } catch (err) {
  46. if (needDestroy) {
  47. writeStream.destroy();
  48. // should delete the exists file before throw error
  49. await this._deleteFileSafe(file);
  50. }
  51. throw err;
  52. }
  53. return {
  54. res: result.res,
  55. content: result.data
  56. };
  57. };