get.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. options.subres = Object.assign({}, options.subres);
  25. if (options.versionId) {
  26. options.subres.versionId = options.versionId;
  27. }
  28. if (options.process) {
  29. options.subres['x-oss-process'] = options.process;
  30. }
  31. let result;
  32. try {
  33. const params = this._objectRequestParams('GET', name, options);
  34. params.writeStream = writeStream;
  35. params.successStatuses = [200, 206, 304];
  36. result = await this.request(params);
  37. if (needDestroy) {
  38. writeStream.destroy();
  39. }
  40. } catch (err) {
  41. if (needDestroy) {
  42. writeStream.destroy();
  43. // should delete the exists file before throw error
  44. await this._deleteFileSafe(file);
  45. }
  46. throw err;
  47. }
  48. return {
  49. res: result.res,
  50. content: result.data
  51. };
  52. };