get.js 1.6 KB

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