租房小程序前端代码
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.

4767 lines
147 KiB

3 months ago
  1. # oss-js-sdk
  2. [![NPM version][npm-image]][npm-url]
  3. [![build status][travis-image]][travis-url]
  4. [![coverage][cov-image]][cov-url]
  5. [![David deps][david-image]][david-url]
  6. [npm-image]: https://img.shields.io/npm/v/ali-oss.svg?style=flat-square
  7. [npm-url]: https://npmjs.org/package/ali-oss
  8. [travis-image]: https://img.shields.io/travis/ali-sdk/ali-oss/master.svg?style=flat-square
  9. [travis-url]: https://travis-ci.org/ali-sdk/ali-oss.svg?branch=master
  10. [cov-image]: http://codecov.io/github/ali-sdk/ali-oss/coverage.svg?branch=master
  11. [cov-url]: http://codecov.io/github/ali-sdk/ali-oss?branch=master
  12. [david-image]: https://img.shields.io/david/ali-sdk/ali-oss.svg?style=flat-square
  13. [david-url]: https://david-dm.org/ali-sdk/ali-oss
  14. aliyun OSS(Object Storage Service) js client for Node and Browser env.
  15. `NOTE`: For SDK `5.X` document, please go to [README.md](https://github.com/ali-sdk/ali-oss/blob/5.x/README.md)
  16. ## Install
  17. ```bash
  18. npm install ali-oss --save
  19. ```
  20. ## Compatibility
  21. ### Node
  22. Node.js >= 8.0.0 required. You can use 4.x in Node.js < 8.
  23. ### Browser
  24. - IE >= 10 & Edge
  25. - Major versions of Chrome/Firefox/Safari
  26. - Major versions of Android/iOS/WP
  27. `Note`:
  28. - For Lower browsers you can refer to [PostObject](https://help.aliyun.com/document_detail/31988.html), if you want to see more practices ,please refer to [Web Post](https://help.aliyun.com/document_detail/31923.html)
  29. ### QA
  30. You can join DingDing Talk Group, [Group Link](https://qr.dingtalk.com/action/joingroup?code=v1,k1,E60EuCmxajfilkaR/kknRcGR9UissskPEXu/1td36z0=)
  31. <img src="task/dingding.jpg" height="400" title="dingding" width="300">
  32. ## License
  33. [MIT](LICENSE)
  34. # OSS Usage
  35. OSS, Object Storage Service. Equal to well known Amazon [S3](http://aws.amazon.com/s3/).
  36. All operation use es7 async/await to implement. All api is async function.
  37. ## Summary
  38. - [Node Usage](#node-usage)
  39. - [Browser Usage](#browser-usage)
  40. - [Data Regions](#data-regions)
  41. - [Create Account](#create-account)
  42. - [Create A Bucket Instance](#create-a-bucket-instance)
  43. - [oss(options)](#ossoptions)
  44. - [Bucket Operations](#bucket-operations)
  45. - Base
  46. - [.listBuckets(query[, options])](#listbucketsquery-options)
  47. - [.putBucket(name[, options])](#putbucketname-options)
  48. - [.useBucket(name)](#usebucketname)
  49. - [.deleteBucket(name[, options])](#deletebucketname-options)
  50. - [.getBucketInfo(name)](#getbucketinfoname)
  51. - [.getBucketStat(name)](#getbucketstatname)
  52. - [.getBucketLocation(name)](#getbucketlocationname)
  53. - ACL
  54. - [.putBucketACL(name, acl[, options])](#putbucketaclname-acl-options)
  55. - [.getBucketACL(name[, options])](#getbucketaclname-options)
  56. - Logging
  57. - [.putBucketLogging(name, prefix[, options])](#putbucketloggingname-prefix-options)
  58. - [.getBucketLogging(name[, options])](#getbucketloggingname-options)
  59. - [.deleteBucketLogging(name[, options])](#deletebucketloggingname-options)
  60. - Website
  61. - [.putBucketWebsite(name, config[, options])](#putbucketwebsitename-config-options)
  62. - [.getBucketWebsite(name[, options])](#getbucketwebsitename-options)
  63. - [.deleteBucketWebsite(name, region[, options])](#deletebucketwebsitename-options)
  64. - Referer
  65. - [.putBucketReferer(name, allowEmpty, referers[, options])](#putbucketreferername-allowempty-referers-options)
  66. - [.getBucketReferer(name[, options])](#getbucketreferername-options)
  67. - [.deleteBucketReferer(name[, options])](#deletebucketreferername-options)
  68. - Lifecycle
  69. - [.putBucketLifecycle(name, rules[, options])](#putbucketlifecyclename-rules-options)
  70. - [.getBucketLifecycle(name[, options])](#getbucketlifecyclename-options)
  71. - [.deleteBucketLifecycle(name[, options])](#deletebucketlifecyclename-options)
  72. - CORS
  73. - [.putBucketCORS(name, rules[, options])](#putbucketcorsname-rules-options)
  74. - [.getBucketCORS(name[, options])](#getbucketcorsname-options)
  75. - [.deleteBucketCORS(name[, options])](#deletebucketcorsname-options)
  76. - RequestPayment
  77. - [.getBucketRequestPayment(bucketName[, options])](#getbucketrequestpaymentbucketname-options)
  78. - [.putBucketRequestPayment(bucketName, payer[, options])](#putBucketRequestpaymentbucketname-payer-options)
  79. - BucketEncryption
  80. - [.putBucketEncryption(name[, rules])](#putbucketencryptionname-rules)
  81. - [.getBucketEncryption(name)](#getbucketencryptionname)
  82. - [.deleteBucketEncryption(name)](#deletebucketencryptionname)
  83. - tagging
  84. - [.putBucketTags(name, tag[, options])](#putBucketTagsname-tag-options)
  85. - [.getBucketTags(name, [, options])](#getBucketTagsname-options)
  86. - [.deleteBucketTags(name, [, options])](#deleteBucketTagsname-options)
  87. - policy
  88. - [.putBucketPolicy(name, policy[, options])](#putBucketPolicyname-policy-options)
  89. - [.getBucketPolicy(name, [, options])](#getBucketPolicyname-options)
  90. - [.deleteBucketPolicy(name, [, options])](#deleteBucketPolicyname-options)
  91. - versioning
  92. - [.getBucketVersioning(name, [, options])](#getBucketVersioningname-options)
  93. - [.putBucketVersioning(name, status[, options])](#putBucketVersioningname-status-options)
  94. - inventory
  95. - [.getBucketInventory(name, inventoryId[, options])](#getBucketInventoryname-inventoryid-options)
  96. - [.putBucketInventory(name, inventory[, options])](#putBucketInventoryname-inventory-options)
  97. - [.deleteBucketInventory(name, inventoryId[, options])](#deleteBucketInventoryname-inventoryid-options)
  98. - [.listBucketInventory(name, [, options])](#listBucketInventoryname-options)
  99. - worm
  100. - [.abortBucketWorm(name[, options])](#abortBucketWormname-options)
  101. - [.completeBucketWorm(name, wormId[, options])](#completeBucketWormname-wormId-options)
  102. - [.extendBucketWorm(name, wormId, days[, options])](#extendBucketWormname-wormId-days-options)
  103. - [.getBucketWorm(name[, options])](#getBucketWormname-options)
  104. - [.initiateBucketWorm(name, days[, options])](#initiateBucketWormname-days-options)
  105. - [Object Operations](#object-operations)
  106. - [.list(query[, options])](#listquery-options)
  107. - [.listV2(query[, options])](#listV2query-options)
  108. - [.getBucketVersions(query[, options])](#getBucketVersionsquery-options)
  109. - [.put(name, file[, options])](#putname-file-options)
  110. - [.putStream(name, stream[, options])](#putstreamname-stream-options)
  111. - [.append(name, file[, options])](#appendname-file-options)
  112. - [.getObjectUrl(name[, baseUrl])](#getobjecturlname-baseurl)
  113. - [.generateObjectUrl(name[, baseUrl])](#generateobjecturlname-baseurl)
  114. - [.head(name[, options])](#headname-options)
  115. - [.getObjectMeta(name[, options])](#getobjectmetaname-options)
  116. - [.get(name[, file, options])](#getname-file-options)
  117. - [.getStream(name[, options])](#getstreamname-options)
  118. - [.delete(name[, options])](#deletename-options)
  119. - [.copy(name, sourceName[, sourceBucket, options])](#copyname-sourcename-sourcebucket-options)
  120. - [.putMeta(name, meta[, options])](#putmetaname-meta-options)
  121. - [.deleteMulti(names[, options])](#deletemultinames-options)
  122. - [.signatureUrl(name[, options])](#signatureurlname-options)
  123. - [.asyncSignatureUrl(name[, options])](#signatureurlname-options)
  124. - [.signatureUrlV4(method, expires[, request, objectName, additionalHeaders])](#signatureurlv4method-expires-request-objectname-additionalheaders)
  125. - [.putACL(name, acl[, options])](#putaclname-acl-options)
  126. - [.getACL(name[, options])](#getaclname-options)
  127. - [.restore(name[, options])](#restorename-options)
  128. - [.putSymlink(name, targetName[, options])](#putsymlinkname-targetname-options)
  129. - [.getSymlink(name[, options])](#getsymlinkname-options)
  130. - [.initMultipartUpload(name[, options])](#initmultipartuploadname-options)
  131. - [.uploadPart(name, uploadId, partNo, file, start, end[, options])](#uploadpartname-uploadid-partno-file-start-end-options)
  132. - [.uploadPartCopy(name, uploadId, partNo, range, sourceData[, options])](#uploadpartcopyname-uploadid-partno-range-sourcedata-options)
  133. - [.completeMultipartUpload(name, uploadId, parts[, options])](#completemultipartuploadname-uploadid-parts-options)
  134. - [.multipartUpload(name, file[, options])](#multipartuploadname-file-options)
  135. - [.multipartUploadCopy(name, sourceData[, options])](#multipartuploadcopyname-sourcedata-options)
  136. - [.listParts(name, uploadId[, query, options])](#listpartsname-uploadid-query-options)
  137. - [.listUploads(query[, options])](#listuploadsquery-options)
  138. - [.abortMultipartUpload(name, uploadId[, options])](#abortmultipartuploadname-uploadid-options)
  139. - [.calculatePostSignature(policy)](#calculatePostSignaturepolicy)
  140. - [.getObjectTagging(name, [, options])](#getObjectTaggingname-options)
  141. - [.putObjectTagging(name, tag[, options])](#putObjectTaggingname-tag-options)
  142. - [.deleteObjectTagging(name, [, options])](#deleteObjectTaggingname-options)
  143. - [RTMP Operations](#rtmp-operations)
  144. - [.putChannel(id, conf[, options])](#putchannelid-conf-options)
  145. - [.getChannel(id[, options])](#getchannelid-options)
  146. - [.deleteChannel(id[, options])](#deletechannelid-options)
  147. - [.putChannelStatus(id, status[, options])](#putchannelstatusid-status-options)
  148. - [.getChannelStatus(id[, options])](#getchannelstatusid-options)
  149. - [.listChannels(query[, options])](#listchannelsquery-options)
  150. - [.getChannelHistory(id[, options])](#getchannelhistoryid-options)
  151. - [.createVod(id, name, time[, options])](#createvodid-name-time-options)
  152. - [.getRtmpUrl(channelId[, options])](#getrtmpurlchannelid-options)
  153. - [Create A Image Service Instance](#create-a-image-service-instance)
  154. - [oss.ImageClient(options)](#ossimageclientoptions)
  155. - [Image Operations](#image-operations)
  156. - [imgClient.get(name, file[, options])](#imgclientgetname-file-options)
  157. - [imgClient.getStream(name[, options])](#imgclientgetstreamname-options)
  158. - [imgClient.getExif(name[, options])](#imgclientgetexifname-options)
  159. - [imgClient.getInfo(name[, options])](#imgclientgetinfoname-options)
  160. - [imgClient.putStyle(name, style[, options])](#imgclientputstylename-style-options)
  161. - [imgClient.getStyle(name[, options])](#imgclientgetstylename-options)
  162. - [imgClient.listStyle([options])](#imgclientliststyleoptions)
  163. - [imgClient.deleteStyle(name[, options])](#imgclientdeletestylename-options)
  164. - [imgClient.signatureUrl(name)](#imgclientsignatureurlname)
  165. - [Known Errors](#known-errors)
  166. ## Node Usage
  167. ### Compatibility
  168. - Node: >= 8.0.0
  169. ### Basic usage
  170. 1.install SDK using npm
  171. ```
  172. npm install ali-oss --save
  173. ```
  174. 2.for example:
  175. ```js
  176. const OSS = require('ali-oss');
  177. const store = new OSS({
  178. region: '<oss region>',
  179. accessKeyId: '<Your accessKeyId>',
  180. accessKeySecret: '<Your accessKeySecret>',
  181. bucket: '<Your bucket name>'
  182. });
  183. ```
  184. ## Browser Usage
  185. You can use most of the functionalities of `ali-oss` in browser with
  186. some exceptions:
  187. - put object with streaming: no chunked encoding, we use multipart
  188. upload instead
  189. - get object to local file: we cannot manipulate file system in
  190. browser, we provide signed object url for downloading needs
  191. - bucket operations(listBuckets, putBucketLogging, etc) will fail: OSS
  192. server currently do not support CORS requests for bucket operations
  193. (will probably be fixed later)
  194. ### Compatibility
  195. - IE >= 10 & Edge
  196. - Major versions of Chrome/Firefox/Safari
  197. - Major versions of Android/iOS/WP
  198. > Note: Because some browsers do not support promises, you need to introduce promise compatible libraries.<br>
  199. > For example: IE10 and IE11 need to introduce a promise-polyfill.
  200. ### Setup
  201. #### Bucket setup
  202. As browser-side javascript involves CORS operations. You need to setup
  203. your bucket CORS rules to allow CORS operations:
  204. - set allowed origins to '\*'
  205. - allowed methods to 'PUT, GET, POST, DELETE, HEAD'
  206. - set allowed headers to '\*'
  207. - expose 'ETag' in expose headers
  208. #### STS setup
  209. As we don't want to expose the accessKeyId/accessKeySecret in the
  210. browser, a [common practice][oss-sts] is to use STS to grant temporary
  211. access.
  212. ### Basic usage
  213. Include the sdk lib in the `<script>` tag and you have `OSS` available
  214. for creating client.
  215. ```html
  216. // x.x.x The specific version number represented // we recommend introducing offline resources, because the usability of
  217. online resources depends on the stability of the cdn server.
  218. <!-- Introducing online resources -->
  219. <script src="http://gosspublic.alicdn.com/aliyun-oss-sdk-x.x.x.min.js"></script>
  220. <!-- Introducing offline resources -->
  221. <script src="./aliyun-oss-sdk-x.x.x.min.js"></script>
  222. <script type="text/javascript">
  223. const store = new OSS({
  224. region: 'oss-cn-hangzhou',
  225. accessKeyId: '<access-key-id>',
  226. accessKeySecret: '<access-key-secret>',
  227. bucket: '<bucket-name>',
  228. stsToken: '<security-token>'
  229. });
  230. store
  231. .list()
  232. .then(result => {
  233. console.log('objects: %j', result.objects);
  234. return store.put('my-obj', new OSS.Buffer('hello world'));
  235. })
  236. .then(result => {
  237. console.log('put result: %j', result);
  238. return store.get('my-obj');
  239. })
  240. .then(result => {
  241. console.log('get result: %j', result.content.toString());
  242. });
  243. </script>
  244. ```
  245. The full sample can be found [here][browser-sample].
  246. ### How to build
  247. ```bash
  248. npm run build-dist
  249. ```
  250. And see the build artifacts under `dist/`.
  251. ## Data Regions
  252. [OSS current data regions](https://help.aliyun.com/document_detail/31837.html).
  253. | region | country | city | endpoint | internal endpoint |
  254. | ------------------ | --------- | -------------- | ------------------------------- | ---------------------------------------- |
  255. | oss-cn-hangzhou | China | HangZhou | oss-cn-hangzhou.aliyuncs.com | oss-cn-hangzhou-internal.aliyuncs.com |
  256. | oss-cn-shanghai | China | ShangHai | oss-cn-shanghai.aliyuncs.com | oss-cn-shanghai-internal.aliyuncs.com |
  257. | oss-cn-qingdao | China | QingDao | oss-cn-qingdao.aliyuncs.com | oss-cn-qingdao-internal.aliyuncs.com |
  258. | oss-cn-beijing | China | BeiJing | oss-cn-beijing.aliyuncs.com | oss-cn-beijing-internal.aliyuncs.com |
  259. | oss-cn-shenzhen | China | ShenZhen | oss-cn-shenzhen.aliyuncs.com | oss-cn-shenzhen-internal.aliyuncs.com |
  260. | oss-cn-hongkong | China | HongKong | oss-cn-hongkong.aliyuncs.com | oss-cn-hongkong-internal.aliyuncs.com |
  261. | oss-us-west-1 | US | Silicon Valley | oss-us-west-1.aliyuncs.com | oss-us-west-1-internal.aliyuncs.com |
  262. | oss-ap-southeast-1 | Singapore | Singapore | oss-ap-southeast-1.aliyuncs.com | oss-ap-southeast-1-internal.aliyuncs.com |
  263. ## Create Account
  264. Go to [OSS website](http://www.aliyun.com/product/oss/?lang=en), create a new account for new user.
  265. After account created, you can create the OSS instance and get the `accessKeyId` and `accessKeySecret`.
  266. ## Create A Bucket Instance
  267. Each OSS instance required `accessKeyId`, `accessKeySecret` and `bucket`.
  268. ## oss(options)
  269. Create a Bucket store instance.
  270. options:
  271. - accessKeyId {String} access key you create on aliyun console website
  272. - accessKeySecret {String} access secret you create
  273. - [stsToken] {String} used by temporary authorization, detail [see](https://www.alibabacloud.com/help/doc-detail/32077.htm)
  274. - [refreshSTSToken] {Function} used by auto set `stsToken`、`accessKeyId`、`accessKeySecret` when sts info expires. return value must be object contains `stsToken`、`accessKeyId`、`accessKeySecret`
  275. - [refreshSTSTokenInterval] {number} use time (ms) of refresh STSToken interval it should be less than sts info expire interval, default is 300000ms(5min)
  276. - [bucket] {String} the default bucket you want to access
  277. If you don't have any bucket, please use `putBucket()` create one first.
  278. - [endpoint] {String} oss region domain. It takes priority over `region`. Set as extranet domain name, intranet domain name, accelerated domain name, etc. according to different needs. please see [endpoints](https://www.alibabacloud.com/help/doc-detail/31837.htm)
  279. - [region] {String} the bucket data region location, please see [Data Regions](#data-regions),
  280. default is `oss-cn-hangzhou`.
  281. - [internal] {Boolean} access OSS with aliyun internal network or not, default is `false`.
  282. If your servers are running on aliyun too, you can set `true` to save a lot of money.
  283. - [secure] {Boolean} instruct OSS client to use HTTPS (secure: true) or HTTP (secure: false) protocol.
  284. - [timeout] {String|Number} instance level timeout for all operations, default is `60s`.
  285. - [cname] {Boolean}, default false, access oss with custom domain name. if true, you can fill `endpoint` field with your custom domain name,
  286. - [isRequestPay] {Boolean}, default false, whether request payer function of the bucket is open, if true, will send headers `'x-oss-request-payer': 'requester'` to oss server.
  287. the details you can see [requestPay](https://help.aliyun.com/document_detail/91337.htm)
  288. - [useFetch] {Boolean}, default false, it just work in Browser, if true,it means upload object with
  289. `fetch` mode ,else `XMLHttpRequest`
  290. - [enableProxy] {Boolean}, Enable proxy request, default is false. **_NOTE:_** When enabling proxy request, please ensure that proxy-agent is installed.
  291. - [proxy] {String | Object}, proxy agent uri or options, default is null.
  292. - [retryMax] {Number}, used by auto retry send request count when request error is net error or timeout. **_NOTE:_** Not support `put` with stream, `putStream`, `append` with stream because the stream can only be consumed once
  293. - [maxSockets] {Number} Maximum number of sockets to allow per host. Default is infinity
  294. - [authorizationV4] {Boolean} Use V4 signature. Default is false.
  295. example:
  296. 1. basic usage
  297. ```js
  298. const OSS = require('ali-oss');
  299. const store = new OSS({
  300. accessKeyId: 'your access key',
  301. accessKeySecret: 'your access secret',
  302. bucket: 'your bucket name',
  303. region: 'oss-cn-hangzhou'
  304. });
  305. ```
  306. 2. use accelerate endpoint
  307. - Global accelerate endpoint: oss-accelerate.aliyuncs.com
  308. - Accelerate endpoint of regions outside mainland China: oss-accelerate-overseas.aliyuncs.com
  309. ```js
  310. const OSS = require('ali-oss');
  311. const store = new OSS({
  312. accessKeyId: 'your access key',
  313. accessKeySecret: 'your access secret',
  314. bucket: 'your bucket name',
  315. endpoint: 'oss-accelerate.aliyuncs.com'
  316. });
  317. ```
  318. 3. use custom domain
  319. ```js
  320. const OSS = require('ali-oss');
  321. const store = new OSS({
  322. accessKeyId: 'your access key',
  323. accessKeySecret: 'your access secret',
  324. cname: true,
  325. endpoint: 'your custome domain'
  326. });
  327. ```
  328. 4. use STS and refreshSTSToken
  329. ```js
  330. const OSS = require('ali-oss');
  331. const store = new OSS({
  332. accessKeyId: 'your STS key',
  333. accessKeySecret: 'your STS secret',
  334. stsToken: 'your STS token',
  335. refreshSTSToken: async () => {
  336. const info = await fetch('you sts server');
  337. return {
  338. accessKeyId: info.accessKeyId,
  339. accessKeySecret: info.accessKeySecret,
  340. stsToken: info.stsToken
  341. };
  342. },
  343. refreshSTSTokenInterval: 300000
  344. });
  345. ```
  346. 5. retry request with stream
  347. ```js
  348. for (let i = 0; i <= store.options.retryMax; i++) {
  349. try {
  350. const result = await store.putStream('<example-object>', fs.createReadStream('<example-path>'));
  351. console.log(result);
  352. break; // break if success
  353. } catch (e) {
  354. console.log(e);
  355. }
  356. }
  357. ```
  358. 6. use V4 signature, and use optional additionalHeaders option which type is a string array, and the values inside need to be included in the header.
  359. ```js
  360. const OSS = require('ali-oss');
  361. const store = new OSS({
  362. accessKeyId: 'your access key',
  363. accessKeySecret: 'your access secret',
  364. bucket: 'your bucket name',
  365. region: 'oss-cn-hangzhou',
  366. authorizationV4: true
  367. });
  368. try {
  369. const bucketInfo = await store.getBucketInfo('your bucket name');
  370. console.log(bucketInfo);
  371. } catch (e) {
  372. console.log(e);
  373. }
  374. try {
  375. const putObjectResult = await store.put('your bucket name', 'your object name', {
  376. headers: {
  377. // The headers of this request
  378. header1: 'value1',
  379. header2: 'value2'
  380. },
  381. // The keys of the request headers that need to be calculated into the V4 signature. Please ensure that these additional headers are included in the request headers.
  382. additionalHeaders: ['additional header1', 'additional header2']
  383. });
  384. console.log(putObjectResult);
  385. } catch (e) {
  386. console.log(e);
  387. }
  388. ```
  389. ## Bucket Operations
  390. ### .listBuckets(query[, options])
  391. List buckets in this account.
  392. parameters:
  393. - [query] {Object} query parameters, default is `null`
  394. - [prefix] {String} search buckets using `prefix` key
  395. - [marker] {String} search start from `marker`, including `marker` key
  396. - [max-keys] {String|Number} max buckets, default is `100`, limit to `1000`
  397. - [options] {Object} optional parameters
  398. - [timeout] {Number} the operation timeout
  399. Success will return buckets list on `buckets` properties.
  400. - buckets {Array<BucketMeta>} bucket meta info list
  401. Each `BucketMeta` will contains blow properties:
  402. - name {String} bucket name
  403. - region {String} bucket store data region, e.g.: `oss-cn-hangzhou-a`
  404. - creationDate {String} bucket create GMT date, e.g.: `2015-02-19T08:39:44.000Z`
  405. - storageClass {String} e.g.: `Standard`, `IA`, `Archive`
  406. - owner {Object} object owner, including `id` and `displayName`
  407. - isTruncated {Boolean} truncate or not
  408. - nextMarker {String} next marker string
  409. - res {Object} response info, including
  410. - status {Number} response status
  411. - headers {Object} response headers
  412. - size {Number} response size
  413. - rt {Number} request total use time (ms)
  414. example:
  415. - List top 10 buckets
  416. ```js
  417. store
  418. .listBuckets({
  419. 'max-keys': 10
  420. })
  421. .then(result => {
  422. console.log(result);
  423. });
  424. ```
  425. ### .putBucket(name[, options])
  426. Create a new bucket.
  427. parameters:
  428. - name {String} bucket name
  429. If bucket exists and not belong to current account, will throw BucketAlreadyExistsError.
  430. If bucket not exists, will create a new bucket and set it's ACL.
  431. - [options] {Object} optional parameters
  432. - [acl] {String} include `private`,`public-read`,`public-read-write`
  433. - [storageClass] {String} the storage type include (Standard,IA,Archive)
  434. - [dataRedundancyType] {String} default `LRS`, include `LRS`,`ZRS`
  435. - [timeout] {Number} the operation timeout
  436. Success will return the bucket name on `bucket` properties.
  437. - bucket {String} bucket name
  438. - res {Object} response info, including
  439. - status {Number} response status
  440. - headers {Object} response headers
  441. - size {Number} response size
  442. - rt {Number} request total use time (ms)
  443. example:
  444. - Create a bucket name `helloworld` location on HongKong
  445. ```js
  446. store.putBucket('helloworld').then(result => {
  447. // use it by default
  448. store.useBucket('helloworld');
  449. });
  450. ```
  451. - Create a bucket name `helloworld` location on HongKong StorageClass `Archive`
  452. ```js
  453. await store.putBucket('helloworld', { StorageClass: 'Archive' });
  454. // use it by default
  455. store.useBucket('helloworld');
  456. ```
  457. ### .deleteBucket(name[, options])
  458. Delete an empty bucket.
  459. parameters:
  460. - name {String} bucket name
  461. If bucket is not empty, will throw BucketNotEmptyError.
  462. If bucket is not exists, will throw NoSuchBucketError.
  463. - [options] {Object} optional parameters
  464. - [timeout] {Number} the operation timeout
  465. Success will return:
  466. - res {Object} response info, including
  467. - status {Number} response status
  468. - headers {Object} response headers
  469. - size {Number} response size
  470. - rt {Number} request total use time (ms)
  471. example:
  472. - Delete the exists 'helloworld' bucket on 'oss-cn-hongkong'
  473. ```js
  474. store.deleteBucket('helloworld').then(result => {});
  475. ```
  476. ### .useBucket(name)
  477. Use the bucket.
  478. parameters:
  479. - name {String} bucket name
  480. example:
  481. - Use `helloworld` as the default bucket
  482. ```js
  483. store.useBucket('helloworld');
  484. ```
  485. ### .getBucketInfo(name)
  486. Get bucket information,include CreationDate、ExtranetEndpoint、IntranetEndpoint、Location、Name、StorageClass、
  487. Owner、AccessControlList、Versioning
  488. parameters:
  489. - name {String} bucket name
  490. example:
  491. - Use `helloworld` as the default bucket
  492. ```js
  493. store.getBucketInfo('helloworld').then(res => {
  494. console.log(res.bucket);
  495. });
  496. ```
  497. ### .getBucketStat(name)
  498. Call the GetBucketStat interface to get the storage capacity of the specified storage space (Bucket) and the number of files (Object).
  499. Calling this interface requires the oss:GetBucketStat permission.
  500. The data obtained by calling this interface is not real-time data and may be delayed for more than an hour.
  501. The point in time of the stored information obtained by calling this interface is not guaranteed to be up-to-date, i.e. the LastModifiedTime field returned by a later call to this interface may be smaller than the LastModifiedTime field returned by a previous call to this interface.
  502. parameters:
  503. - name {String} bucket name
  504. Success will return:
  505. - stat {Object} container for the BucketStat structure:
  506. - Storage {String} the total storage capacity of the Bucket, in bytes.
  507. - ObjectCount {String} total number of Objects in the Bucket。
  508. - MultipartUploadCount {String} the number of Multipart Uploads in the Bucket that have been initialized but not yet completed (Complete) or not yet aborted (Abort).
  509. - LiveChannelCount {String} the number of Live Channels in the Bucket.
  510. - LastModifiedTime {String} the point in time, in timestamps, when the storage information was retrieved.
  511. - StandardStorage {String} the amount of storage of the standard storage type, in bytes.
  512. - StandardObjectCount {String} the number of objects of the standard storage type.
  513. - InfrequentAccessStorage {String} the amount of billed storage for the low-frequency storage type, in bytes.
  514. - InfrequentAccessRealStorage {String} the actual storage amount of the low-frequency storage type, in bytes.
  515. - InfrequentAccessObjectCount {String} the number of Objects of the low-frequency storage type.
  516. - ArchiveStorage {String} the amount of billed storage for the archive storage type, in bytes.
  517. - ArchiveRealStorage {String} the actual storage amount of the archive storage type, in bytes.
  518. - ArchiveObjectCount {String} the number of objects of the archive storage type.
  519. - ColdArchiveStorage {String} the amount of billed storage for the cold archive storage type, in bytes.
  520. - ColdArchiveRealStorage {String} the actual storage amount in bytes for the cold archive storage type.
  521. - ColdArchiveObjectCount {String} the number of objects of the cold archive storage type.
  522. - res {Object} response info, including
  523. - status {Number} response status
  524. - headers {Object} response headers
  525. - size {Number} response size
  526. - rt {Number} request total use time (ms)
  527. example:
  528. - If you don't fill in the name, the default is the bucket defined during initialization.
  529. ```js
  530. store.getBucketStat().then(res => console.log(res));
  531. ```
  532. ### .getBucketLocation(name)
  533. Get bucket location
  534. parameters:
  535. - name {String} bucket name
  536. example:
  537. - Use `helloworld` as the default bucket
  538. ```js
  539. store.getBucketLocation('helloworld').then(res => {
  540. console.log(res.location);
  541. });
  542. ```
  543. ---
  544. ### .putBucketACL(name, acl[, options])
  545. Update the bucket ACL.
  546. parameters:
  547. - name {String} bucket name
  548. - acl {String} access control list, current available: `public-read-write`, `public-read` and `private`
  549. - [options] {Object} optional parameters
  550. - [timeout] {Number} the operation timeout
  551. Success will return:
  552. - res {Object} response info, including
  553. - status {Number} response status
  554. - headers {Object} response headers
  555. - size {Number} response size
  556. - rt {Number} request total use time (ms)
  557. example:
  558. - Set bucket `helloworld` to `public-read-write`
  559. ```js
  560. store.putBucketACL('helloworld', 'public-read-write').then(result => {});
  561. ```
  562. ### .getBucketACL(name[, options])
  563. Get the bucket ACL.
  564. parameters:
  565. - name {String} bucket name
  566. - [options] {Object} optional parameters
  567. - [timeout] {Number} the operation timeout
  568. Success will return:
  569. - acl {String} acl settiongs string
  570. - res {Object} response info, including
  571. - status {Number} response status
  572. - headers {Object} response headers
  573. - size {Number} response size
  574. - rt {Number} request total use time (ms)
  575. example:
  576. - Get bucket `helloworld`
  577. ```js
  578. store.getBucketACL('helloworld').then(result => {
  579. console.log(result.acl);
  580. });
  581. ```
  582. ---
  583. ### .putBucketLogging(name, prefix[, options])
  584. Update the bucket logging settings.
  585. Log file will create every one hour and name format: `<prefix><bucket>-YYYY-mm-DD-HH-MM-SS-UniqueString`.
  586. parameters:
  587. - name {String} bucket name
  588. - [prefix] {String} prefix path name to store the log files
  589. - [options] {Object} optional parameters
  590. - [timeout] {Number} the operation timeout
  591. Success will return:
  592. - res {Object} response info, including
  593. - status {Number} response status
  594. - headers {Object} response headers
  595. - size {Number} response size
  596. - rt {Number} request total use time (ms)
  597. example:
  598. - Enable bucket `helloworld` logging and save with prefix `logs/`
  599. ```js
  600. store.putBucketLogging('helloworld', 'logs/').then(result => {});
  601. ```
  602. ### .getBucketLogging(name[, options])
  603. Get the bucket logging settings.
  604. parameters:
  605. - name {String} bucket name
  606. - [options] {Object} optional parameters
  607. - [timeout] {Number} the operation timeout
  608. Success will return:
  609. - enable {Boolean} enable logging or not
  610. - prefix {String} prefix path name to store the log files, maybe `null`
  611. - res {Object} response info, including
  612. - status {Number} response status
  613. - headers {Object} response headers
  614. - size {Number} response size
  615. - rt {Number} request total use time (ms)
  616. example:
  617. - Get bucket `helloworld` logging settings
  618. ```js
  619. store.getBucketLogging('helloworld').then(result => {
  620. console.log(result.enable, result.prefix);
  621. });
  622. ```
  623. ### .deleteBucketLogging(name[, options])
  624. Delete the bucket logging settings.
  625. parameters:
  626. - name {String} bucket name
  627. - [options] {Object} optional parameters
  628. - [timeout] {Number} the operation timeout
  629. Success will return:
  630. - res {Object} response info, including
  631. - status {Number} response status
  632. - headers {Object} response headers
  633. - size {Number} response size
  634. - rt {Number} request total use time (ms)
  635. ---
  636. ### .putBucketWebsite(name, config[, options])
  637. Set the bucket as a static website.
  638. parameters:
  639. - name {String} bucket name
  640. - config {Object} website config, contains blow properties:
  641. - index {String} default page, e.g.: `index.html`
  642. - [error] {String} error page, e.g.: 'error.html'
  643. - [supportSubDir] {String} default vaule false
  644. - [type] {String} default value 0
  645. - [routingRules] {Array} RoutingRules
  646. - [options] {Object} optional parameters
  647. - [timeout] {Number} the operation timeout
  648. Success will return:
  649. - res {Object} response info, including
  650. - status {Number} response status
  651. - headers {Object} response headers
  652. - size {Number} response size
  653. - rt {Number} request total use time (ms)
  654. example:
  655. ```js
  656. store
  657. .putBucketWebsite('hello', {
  658. index: 'index.html'
  659. })
  660. .then(result => {});
  661. ```
  662. ### .getBucketWebsite(name[, options])
  663. Get the bucket website config.
  664. parameters:
  665. - name {String} bucket name
  666. - [options] {Object} optional parameters
  667. - [timeout] {Number} the operation timeout
  668. Success will return:
  669. - index {String} index page
  670. - error {String} error page, maybe `null`
  671. - supportSubDir {String}
  672. - type {String}
  673. - routingRules {Array}
  674. - res {Object} response info, including
  675. - status {Number} response status
  676. - headers {Object} response headers
  677. - size {Number} response size
  678. - rt {Number} request total use time (ms)
  679. ### .deleteBucketWebsite(name[, options])
  680. Delete the bucket website config.
  681. parameters:
  682. - name {String} bucket name
  683. - [options] {Object} optional parameters
  684. - [timeout] {Number} the operation timeout
  685. Success will return:
  686. - res {Object} response info, including
  687. - status {Number} response status
  688. - headers {Object} response headers
  689. - size {Number} response size
  690. - rt {Number} request total use time (ms)
  691. ---
  692. ### .putBucketReferer(name, allowEmpty, referers[, options])
  693. Set the bucket request `Referer` white list.
  694. parameters:
  695. - name {String} bucket name
  696. - allowEmpty {Boolean} allow empty request referer or not
  697. - referers {Array<String>} `Referer` white list, e.g.:
  698. ```js
  699. ['https://npm.taobao.org', 'http://cnpmjs.org'];
  700. ```
  701. - [options] {Object} optional parameters
  702. - [timeout] {Number} the operation timeout
  703. Success will return:
  704. - res {Object} response info, including
  705. - status {Number} response status
  706. - headers {Object} response headers
  707. - size {Number} response size
  708. - rt {Number} request total use time (ms)
  709. example:
  710. ```js
  711. store.putBucketReferer('hello', false, ['https://npm.taobao.org', 'http://cnpmjs.org']).then(result => {});
  712. ```
  713. ### .getBucketReferer(name[, options])
  714. Get the bucket request `Referer` white list.
  715. parameters:
  716. - name {String} bucket name
  717. - [options] {Object} optional parameters
  718. - [timeout] {Number} the operation timeout
  719. Success will return:
  720. - allowEmpty {Boolean} allow empty request referer or not
  721. - referers {Array<String>} `Referer` white list
  722. - res {Object} response info, including
  723. - status {Number} response status
  724. - headers {Object} response headers
  725. - size {Number} response size
  726. - rt {Number} request total use time (ms)
  727. ### .deleteBucketReferer(name[, options])
  728. Delete the bucket request `Referer` white list.
  729. parameters:
  730. - name {String} bucket name
  731. - [options] {Object} optional parameters
  732. - [timeout] {Number} the operation timeout
  733. Success will return:
  734. - res {Object} response info, including
  735. - status {Number} response status
  736. - headers {Object} response headers
  737. - size {Number} response size
  738. - rt {Number} request total use time (ms)
  739. ---
  740. ### .putBucketLifecycle(name, rules[, options])
  741. Set the bucket object lifecycle.
  742. parameters:
  743. - name {String} bucket name
  744. - rules {Array<Rule>} rule config list, each `Rule` will contains blow properties:
  745. - [id] {String} rule id, if not set, OSS will auto create it with random string.
  746. - prefix {String} store prefix
  747. - status {String} rule status, allow values: `Enabled` or `Disabled`
  748. - [expiration] {Object} specifies the expiration attribute of the lifecycle rules for the object.
  749. - [days] {Number|String} expire after the `days`
  750. - [createdBeforeDate] {String} expire date, e.g.: `2022-10-11T00:00:00.000Z`
  751. - [expiredObjectDeleteMarker] {String} value `true`
  752. `createdBeforeDate` and `days` and `expiredObjectDeleteMarker` must have one.
  753. - [abortMultipartUpload] {Object} Specifies the expiration attribute of the multipart upload tasks that are not complete.
  754. - [days] {Number|String} expire after the `days`
  755. - [createdBeforeDate] {String} expire date, e.g.: `2022-10-11T00:00:00.000Z`
  756. `createdBeforeDate` and `days` must have one.
  757. - [transition] {Object} Specifies the time when an object is converted to the IA or archive storage class during a valid life cycle.
  758. - storageClass {String} Specifies the storage class that objects that conform to the rule are converted into. allow values: `IA` or `Archive` or `ColdArchive` or `DeepColdArchive`
  759. - [days] {Number|String} expire after the `days`
  760. - [createdBeforeDate] {String} expire date, e.g.: `2022-10-11T00:00:00.000Z`
  761. `createdBeforeDate` and `days` must have one.
  762. - [noncurrentVersionTransition] {Object} Specifies the time when an object is converted to the IA or archive storage class during a valid life cycle.
  763. - storageClass {String} Specifies the storage class that history objects that conform to the rule are converted into. allow values: `IA` or `Archive` or `ColdArchive` or `DeepColdArchive`
  764. - noncurrentDays {String} expire after the `noncurrentDays`
  765. `expiration``abortMultipartUpload``transition``noncurrentVersionTransition` must have one.
  766. - [noncurrentVersionExpiration] {Object} specifies the expiration attribute of the lifecycle rules for the history object.
  767. - noncurrentDays {String} expire after the `noncurrentDays`
  768. - [tag] {Object} Specifies the object tag applicable to a rule. Multiple tags are supported.
  769. - key {String} Indicates the tag key.
  770. - value {String} Indicates the tag value.
  771. `tag` cannot be used with `abortMultipartUpload`
  772. - [options] {Object} optional parameters
  773. - [timeout] {Number} the operation timeout
  774. Success will return:
  775. - res {Object} response info, including
  776. - status {Number} response status
  777. - headers {Object} response headers
  778. - size {Number} response size
  779. - rt {Number} request total use time (ms)
  780. example:
  781. ```js
  782. store
  783. .putBucketLifecycle('hello', [
  784. {
  785. id: 'delete after one day',
  786. prefix: 'logs/',
  787. status: 'Enabled',
  788. days: 1
  789. },
  790. {
  791. prefix: 'logs2/',
  792. status: 'Disabled',
  793. date: '2022-10-11T00:00:00.000Z'
  794. }
  795. ])
  796. .then(result => {});
  797. ```
  798. example: for history with noncurrentVersionExpiration
  799. ```js
  800. const result = await store.putBucketLifecycle(bucket, [
  801. {
  802. id: 'expiration1',
  803. prefix: 'logs/',
  804. status: 'Enabled',
  805. expiration: {
  806. days: '1'
  807. },
  808. noncurrentVersionExpiration: {
  809. noncurrentDays: '1'
  810. }
  811. }
  812. ]);
  813. console.log(result);
  814. ```
  815. example: for history with expiredObjectDeleteMarker
  816. ```js
  817. const result = await store.putBucketLifecycle(bucket, [
  818. {
  819. id: 'expiration1',
  820. prefix: 'logs/',
  821. status: 'Enabled',
  822. expiration: {
  823. expiredObjectDeleteMarker: 'true'
  824. },
  825. noncurrentVersionExpiration: {
  826. noncurrentDays: '1'
  827. }
  828. }
  829. ]);
  830. console.log(result);
  831. ```
  832. example: for history with noncurrentVersionTransition
  833. ```js
  834. const result = await store.putBucketLifecycle(bucket, [
  835. {
  836. id: 'expiration1',
  837. prefix: 'logs/',
  838. status: 'Enabled',
  839. noncurrentVersionTransition: {
  840. noncurrentDays: '10',
  841. storageClass: 'IA'
  842. }
  843. }
  844. ]);
  845. console.log(result);
  846. ```
  847. ### .getBucketLifecycle(name[, options])
  848. Get the bucket object lifecycle.
  849. parameters:
  850. - name {String} bucket name
  851. - [options] {Object} optional parameters
  852. - [timeout] {Number} the operation timeout
  853. Success will return:
  854. - rules {Array<Rule>} the lifecycle rule list
  855. - res {Object} response info, including
  856. - status {Number} response status
  857. - headers {Object} response headers
  858. - size {Number} response size
  859. - rt {Number} request total use time (ms)
  860. ### .deleteBucketLifecycle(name[, options])
  861. Delete the bucket object lifecycle.
  862. parameters:
  863. - name {String} bucket name
  864. - [options] {Object} optional parameters
  865. - [timeout] {Number} the operation timeout
  866. Success will return:
  867. - res {Object} response info, including
  868. - status {Number} response status
  869. - headers {Object} response headers
  870. - size {Number} response size
  871. - rt {Number} request total use time (ms)
  872. ---
  873. ### .putBucketCORS(name, rules[, options])
  874. Set CORS rules of the bucket object
  875. parameters:
  876. - name {String} bucket name
  877. - rules {Array<Rule>} rule config list, each `Rule` will contains below properties:
  878. - allowedOrigin {String/Array} configure for Access-Control-Allow-Origin header
  879. - allowedMethod {String/Array} configure for Access-Control-Allow-Methods header
  880. - [allowedHeader] {String/Array} configure for Access-Control-Allow-Headers header
  881. - [exposeHeader] {String/Array} configure for Access-Control-Expose-Headers header
  882. - [maxAgeSeconds] {String} configure for Access-Control-Max-Age header
  883. - [options] {Object} optional parameters
  884. - [timeout] {Number} the operation timeout
  885. Success will return:
  886. - res {Object} response info, including
  887. - status {Number} response status
  888. - headers {Object} response headers
  889. - size {Number} response size
  890. - rt {Number} request total use time (ms)
  891. example:
  892. ```js
  893. store
  894. .putBucketCORS('hello', [
  895. {
  896. allowedOrigin: '*',
  897. allowedMethod: ['GET', 'HEAD']
  898. }
  899. ])
  900. .then(result => {});
  901. ```
  902. ### .getBucketCORS(name[, options])
  903. Get CORS rules of the bucket object.
  904. parameters:
  905. - name {String} bucket name
  906. - [options] {Object} optional parameters
  907. - [timeout] {Number} the operation timeout
  908. Success will return:
  909. - rules {Array<Rule>} the CORS rule list
  910. - res {Object} response info, including
  911. - status {Number} response status
  912. - headers {Object} response headers
  913. - size {Number} response size
  914. - rt {Number} request total use time (ms)
  915. ### .deleteBucketCORS(name[, options])
  916. Delete CORS rules of the bucket object.
  917. parameters:
  918. - name {String} bucket name
  919. - [options] {Object} optional parameters
  920. - [timeout] {Number} the operation timeout
  921. Success will return:
  922. - res {Object} response info, including
  923. - status {Number} response status
  924. - headers {Object} response headers
  925. - size {Number} response size
  926. - rt {Number} request total use time (ms)
  927. ### .getBucketRequestPayment(bucketName[, options])
  928. get RequestPayment value of the bucket object.
  929. parameters:
  930. - bucketName {String} bucket name
  931. - [options] {Object} optional parameters
  932. Success will return:
  933. - status {Number} response status
  934. - payer {String} payer, BucketOwner or Requester
  935. - res {Object} response info, including
  936. - data {Buffer} xml
  937. ---
  938. ### .putBucketRequestPayment(bucketName, payer[, options])
  939. put RequestPayment value of the bucket object.
  940. parameters:
  941. - bucketName {String}
  942. - payer {String} payer
  943. - [options] {Object} optional parameters
  944. Success will return:
  945. - status {Number} response status
  946. - res {Object} response info
  947. ---
  948. ### .putBucketEncryption(name, rules)
  949. put BucketEncryption value of the bucket object.
  950. parameters:
  951. - name {String} bucket name
  952. - [rules] {Object} parameters
  953. - SSEAlgorithm {String} encryption type, expect AES256 or KMS
  954. - {KMSMasterKeyID} {String} needed when encryption type is KMS
  955. Success will return:
  956. - status {Number} response status
  957. - res {Object} response info
  958. ---
  959. ### .getBucketEncryption(name)
  960. get BucketEncryption rule value of the bucket object.
  961. parameters:
  962. - name {String} bucket name
  963. Success will return:
  964. - status {Number} response status
  965. - res {Object} response info
  966. - encryption {Object} rules
  967. - SSEAlgorithm {String} encryption type, AES256 or KMS
  968. - {KMSMasterKeyID} {String} will be return when encryption type is KMS
  969. ---
  970. ### .deleteBucketEncryption(name)
  971. delete BucketEncryption rule value of the bucket object.
  972. parameters:
  973. - name {String} bucket name
  974. Success will return:
  975. - status {Number} response status
  976. - res {Object} response info
  977. ---
  978. ### .putBucketTags(name, tag[, options])
  979. Adds tags for a bucket or modify the tags for a bucket.
  980. parameters:
  981. - name {String} the object name
  982. - tag {Object} tag, eg. `{var1: value1,var2:value2}`
  983. - [options] {Object} optional args
  984. Success will return:
  985. - status {Number} response status
  986. - res {Object} response info
  987. ---
  988. ### .getBucketTags(name[, options])
  989. Obtains the tags for a bucket.
  990. parameters:
  991. - name {String} the object name
  992. - [options] {Object} optional args
  993. Success will return:
  994. - tag {Object} the tag of object
  995. - res {Object} response info
  996. ---
  997. ### .deleteBucketTags(name[, options])
  998. Deletes the tags added for a bucket.
  999. parameters:
  1000. - name {String} the object name
  1001. - [options] {Object} optional args
  1002. Success will return:
  1003. - status {Number} response status
  1004. - res {Object} response info
  1005. ---
  1006. ### .putBucketPolicy(name, policy[, options])
  1007. Adds or modify policy for a bucket.
  1008. parameters:
  1009. - name {String} the bucket name
  1010. - policy {Object} bucket policy
  1011. - [options] {Object} optional args
  1012. Success will return:
  1013. - status {Number} response status
  1014. - res {Object} response info
  1015. example:
  1016. ```js
  1017. const policy = {
  1018. Version: '1',
  1019. Statement: [
  1020. {
  1021. Action: ['oss:PutObject', 'oss:GetObject'],
  1022. Effect: 'Deny',
  1023. Principal: ['1234567890'],
  1024. Resource: ['acs:oss:*:1234567890:*/*']
  1025. }
  1026. ]
  1027. };
  1028. const result = await store.putBucketPolicy(bucket, policy);
  1029. console.log(result);
  1030. ```
  1031. ---
  1032. ### .getBucketPolicy(name[, options])
  1033. Obtains the policy for a bucket.
  1034. parameters:
  1035. - name {String} the bucket name
  1036. - [options] {Object} optional args
  1037. Success will return:
  1038. - policy {Object} the policy of bucket, if not exist, the value is null
  1039. - res {Object} response info
  1040. - status {Number} response status
  1041. ---
  1042. ### .deleteBucketPolicy(name[, options])
  1043. Deletes the policy added for a bucket.
  1044. parameters:
  1045. - name {String} the bucket name
  1046. - [options] {Object} optional args
  1047. Success will return:
  1048. - status {Number} response status
  1049. - res {Object} response info
  1050. ---
  1051. ### .getBucketVersioning(name[, options])
  1052. Obtains the version status of an object
  1053. parameters:
  1054. - name {String} the bucket name
  1055. - [options] {Object} optional args
  1056. Success will return:
  1057. - status {Number} response status
  1058. - versionStatus {String | undefined} version status, `Suspended` or `Enabled`. default value: `undefined`
  1059. - res {Object} response info
  1060. ---
  1061. ### .putBucketVersioning(name, status[, options])
  1062. set the version status of an object
  1063. parameters:
  1064. - name {String} the bucket name
  1065. - status {String} version status, allow values: `Enabled` or `Suspended`
  1066. - [options] {Object} optional args
  1067. Success will return:
  1068. - status {Number} response status
  1069. - res {Object} response info
  1070. ---
  1071. ### .getBucketInventory(name, inventoryId[, options])
  1072. get bucket inventory by inventory-id
  1073. parameters:
  1074. - name {String} the bucket name
  1075. - inventoryId {String} inventory-id
  1076. - [options] {Object} optional args
  1077. Success will return:
  1078. - inventory {Inventory}
  1079. - status {Number} response status
  1080. - res {Object} response info
  1081. ```js
  1082. async function getBucketInventoryById() {
  1083. try {
  1084. const result = await store.getBucketInventory('bucket', 'inventoryid');
  1085. console.log(result.inventory);
  1086. } catch (err) {
  1087. console.log(err);
  1088. }
  1089. }
  1090. getBucketInventoryById();
  1091. ```
  1092. ### putBucketInventory(name, inventory[, options])
  1093. set bucket inventory
  1094. parameters:
  1095. - name {String} the bucket name
  1096. - inventory {Inventory} inventory config
  1097. - [options] {Object} optional args
  1098. Success will return:
  1099. - status {Number} response status
  1100. - res {Object} response info
  1101. ```ts
  1102. type Field =
  1103. 'Size | LastModifiedDate | ETag | StorageClass | IsMultipartUploaded | EncryptionStatus | ObjectAcl | TaggingCount | ObjectType | Crc64';
  1104. interface Inventory {
  1105. id: string;
  1106. isEnabled: true | false;
  1107. prefix?: string;
  1108. OSSBucketDestination: {
  1109. format: 'CSV';
  1110. accountId: string;
  1111. rolename: string;
  1112. bucket: string;
  1113. prefix?: string;
  1114. encryption?:
  1115. | { 'SSE-OSS': '' }
  1116. | {
  1117. 'SSE-KMS': {
  1118. keyId: string;
  1119. };
  1120. };
  1121. };
  1122. frequency: 'Daily' | 'Weekly';
  1123. includedObjectVersions: 'Current' | 'All';
  1124. optionalFields?: {
  1125. field?: Field[];
  1126. };
  1127. }
  1128. ```
  1129. ```js
  1130. const inventory = {
  1131. id: 'default',
  1132. isEnabled: false, // `true` | `false`
  1133. prefix: 'ttt', // filter prefix
  1134. OSSBucketDestination: {
  1135. format: 'CSV',
  1136. accountId: '1817184078010220',
  1137. rolename: 'AliyunOSSRole',
  1138. bucket: 'your bucket',
  1139. prefix: 'test'
  1140. //encryption: {'SSE-OSS': ''},
  1141. /*
  1142. encryption: {
  1143. 'SSE-KMS': {
  1144. keyId: 'test-kms-id';
  1145. };,
  1146. */
  1147. },
  1148. frequency: 'Daily', // `WEEKLY` | `Daily`
  1149. includedObjectVersions: 'All', // `All` | `Current`
  1150. optionalFields: {
  1151. field: [
  1152. 'Size',
  1153. 'LastModifiedDate',
  1154. 'ETag',
  1155. 'StorageClass',
  1156. 'IsMultipartUploaded',
  1157. 'EncryptionStatus',
  1158. 'ObjectAcl',
  1159. 'TaggingCount',
  1160. 'ObjectType',
  1161. 'Crc64'
  1162. ]
  1163. }
  1164. };
  1165. async function putInventory() {
  1166. const bucket = 'Your Bucket Name';
  1167. try {
  1168. await store.putBucketInventory(bucket, inventory);
  1169. } catch (err) {
  1170. console.log(err);
  1171. }
  1172. }
  1173. putInventory();
  1174. ```
  1175. ### deleteBucketInventory(name, inventoryId[, options])
  1176. delete bucket inventory by inventory-id
  1177. parameters:
  1178. - name {String} the bucket name
  1179. - inventoryId {String} inventory-id
  1180. - [options] {Object} optional args
  1181. Success will return:
  1182. - status {Number} response status
  1183. - res {Object} response info
  1184. ### listBucketInventory(name[, options])
  1185. list bucket inventory
  1186. parameters:
  1187. - name {String} the bucket name
  1188. - [options] {Object} optional args
  1189. - continuationToken used by search next page
  1190. Success will return:
  1191. - status {Number} response status
  1192. - res {Object} response info
  1193. example:
  1194. ```js
  1195. async function listBucketInventory() {
  1196. const bucket = 'Your Bucket Name';
  1197. let nextContinuationToken;
  1198. // list all inventory of the bucket
  1199. do {
  1200. const result = await store.listBucketInventory(bucket, nextContinuationToken);
  1201. console.log(result.inventoryList);
  1202. nextContinuationToken = result.nextContinuationToken;
  1203. } while (nextContinuationToken);
  1204. }
  1205. listBucketInventory();
  1206. ```
  1207. ### .abortBucketWorm(name[, options])
  1208. used to delete an unlocked retention policy.
  1209. parameters:
  1210. - name {String} the bucket name
  1211. - [options] {Object} optional args
  1212. Success will return:
  1213. - status {Number} response status
  1214. - res {Object} response info
  1215. ---
  1216. ### .completeBucketWorm(name, wormId[, options])
  1217. used to lock a retention policy.
  1218. parameters:
  1219. - name {String} the bucket name
  1220. - wormId {String} worm id
  1221. - [options] {Object} optional args
  1222. Success will return:
  1223. - status {Number} response status
  1224. - res {Object} response info
  1225. ---
  1226. ### .extendBucketWorm(name, wormId, days[, options])
  1227. used to extend the retention period of objects in a bucket whose retention policy is locked.
  1228. parameters:
  1229. - name {String} the bucket name
  1230. - wormId {String} worm id
  1231. - days {String | Number} retention days
  1232. - [options] {Object} optional args
  1233. Success will return:
  1234. - status {Number} response status
  1235. - res {Object} response info
  1236. ---
  1237. ### .getBucketWorm(name[, options])
  1238. used to query the retention policy information of the specified bucket.
  1239. parameters:
  1240. - name {String} the bucket name
  1241. - [options] {Object} optional args
  1242. Success will return:
  1243. - wormId {String} worm id
  1244. - state {String} `Locked` or `InProgress`
  1245. - days {String} retention days
  1246. - creationDate {String}
  1247. - status {Number} response status
  1248. - res {Object} response info
  1249. ---
  1250. ### .initiateBucketWorm(name, days[, options])
  1251. create a retention policy.
  1252. parameters:
  1253. - name {String} the bucket name
  1254. - days {String | Number}} set retention days
  1255. - [options] {Object} optional args
  1256. Success will return:
  1257. - wormId {String} worm id
  1258. - status {Number} response status
  1259. - res {Object} response info
  1260. ---
  1261. ## Object Operations
  1262. All operations function return Promise, except `signatureUrl`.
  1263. ### .put(name, file[, options])
  1264. Add an object to the bucket.
  1265. parameters:
  1266. - name {String} object name store on OSS
  1267. - file {String|Buffer|ReadStream|File(only support Browser)|Blob(only support Browser)} object local path, content buffer or ReadStream content instance use in Node, Blob and html5 File
  1268. - [options] {Object} optional parameters
  1269. - [timeout] {Number} the operation timeout (ms)
  1270. - [mime] {String} custom mime, will send with `Content-Type` entity header
  1271. - [meta] {Object} user meta, will send with `x-oss-meta-` prefix string
  1272. e.g.: `{ uid: 123, pid: 110 }`
  1273. - [callback] {Object} The callback parameter is composed of a JSON string encoded in Base64,detail [see](https://www.alibabacloud.com/help/doc-detail/31989.htm)<br>
  1274. - url {String} After a file is uploaded successfully, the OSS sends a callback request to this URL.
  1275. - [host] {String} The host header value for initiating callback requests.
  1276. - body {String} The value of the request body when a callback is initiated, for example, `key=${key}&etag=${etag}&my_var=${x:my_var}`.
  1277. - [contentType] {String} The Content-Type of the callback requests initiatiated, It supports application/x-www-form-urlencoded and application/json, and the former is the default value.
  1278. - [callbackSNI] {Boolean} Specifies whether OSS sends Server Name Indication (SNI) to the origin address specified by callbackUrl when a callback request is initiated from the client.
  1279. - [customValue] {Object} Custom parameters are a map of key-values<br>
  1280. e.g.:
  1281. ```js
  1282. var customValue = { var1: 'value1', var2: 'value2' };
  1283. ```
  1284. - [headers] {Object} extra headers
  1285. - 'Cache-Control' cache control for download, e.g.: `Cache-Control: public, no-cache`
  1286. - 'Content-Disposition' object name for download, e.g.: `Content-Disposition: somename`
  1287. - 'Content-Encoding' object content encoding for download, e.g.: `Content-Encoding: gzip`
  1288. - 'Expires' expires time for download, an absolute date and time. e.g.: `Tue, 08 Dec 2020 13:49:43 GMT`
  1289. - See more: [PutObject](https://help.aliyun.com/document_detail/31978.html#title-yxe-96d-x61)
  1290. - [disabledMD5] {Boolean} default true, it just work in Browser. if false,it means that MD5 is automatically calculated for uploaded files. **_NOTE:_** Synchronous computing tasks will block the main process
  1291. Success will return the object information.
  1292. object:
  1293. - name {String} object name
  1294. - data {Object} callback server response data, sdk use JSON.parse() return
  1295. - res {Object} response info, including
  1296. - status {Number} response status
  1297. - headers {Object} response headers
  1298. - size {Number} response size
  1299. - rt {Number} request total use time (ms)
  1300. example:
  1301. - Add an object through local file path
  1302. ```js
  1303. const filepath = '/home/ossdemo/demo.txt';
  1304. store.put('ossdemo/demo.txt', filepath).then((result) => {
  1305. console.log(result);
  1306. });
  1307. // {
  1308. // name: 'ossdemo/demo.txt',
  1309. // res: {
  1310. // status: 200,
  1311. // headers: {
  1312. // date: 'Tue, 17 Feb 2015 13:28:17 GMT',
  1313. // 'content-length': '0',
  1314. // connection: 'close',
  1315. // etag: '"BF7A03DA01440845BC5D487B369BC168"',
  1316. // server: 'AliyunOSS',
  1317. // 'x-oss-request-id': '54E341F1707AA0275E829244'
  1318. // },
  1319. // size: 0,
  1320. // rt: 92
  1321. // }
  1322. // }
  1323. ```
  1324. - Add an object through content buffer
  1325. ```js
  1326. store.put('ossdemo/buffer', Buffer.from('foo content')).then((result) => {
  1327. console.log(result);
  1328. });
  1329. // {
  1330. // name: 'ossdemo/buffer',
  1331. // url: 'http://demo.oss-cn-hangzhou.aliyuncs.com/ossdemo/buffer',
  1332. // res: {
  1333. // status: 200,
  1334. // headers: {
  1335. // date: 'Tue, 17 Feb 2015 13:28:17 GMT',
  1336. // 'content-length': '0',
  1337. // connection: 'close',
  1338. // etag: '"xxx"',
  1339. // server: 'AliyunOSS',
  1340. // 'x-oss-request-id': '54E341F1707AA0275E829243'
  1341. // },
  1342. // size: 0,
  1343. // rt: 92
  1344. // }
  1345. // }
  1346. ```
  1347. - Add an object through readstream
  1348. ```js
  1349. const filepath = '/home/ossdemo/demo.txt';
  1350. store.put('ossdemo/readstream.txt', fs.createReadStream(filepath)).then((result) => {
  1351. console.log(result);
  1352. });
  1353. // {
  1354. // name: 'ossdemo/readstream.txt',
  1355. // url: 'http://demo.oss-cn-hangzhou.aliyuncs.com/ossdemo/readstream.txt',
  1356. // res: {
  1357. // status: 200,
  1358. // headers: {
  1359. // date: 'Tue, 17 Feb 2015 13:28:17 GMT',
  1360. // 'content-length': '0',
  1361. // connection: 'close',
  1362. // etag: '"BF7A03DA01440845BC5D487B369BC168"',
  1363. // server: 'AliyunOSS',
  1364. // 'x-oss-request-id': '54E341F1707AA0275E829242'
  1365. // },
  1366. // size: 0,
  1367. // rt: 92
  1368. // }
  1369. // }
  1370. ```
  1371. ### .putStream(name, stream[, options])
  1372. Add a stream object to the bucket.
  1373. parameters:
  1374. - name {String} object name store on OSS
  1375. - stream {ReadStream} object ReadStream content instance
  1376. - [options] {Object} optional parameters
  1377. - [contentLength] {Number} the stream length, `chunked encoding` will be used if absent
  1378. - [timeout] {Number} the operation timeout
  1379. - [mime] {String} custom mime, will send with `Content-Type` entity header
  1380. - [meta] {Object} user meta, will send with `x-oss-meta-` prefix string
  1381. e.g.: `{ uid: 123, pid: 110 }`
  1382. - [callback] {Object} The callback parameter is composed of a JSON string encoded in Base64,detail [see](https://www.alibabacloud.com/help/doc-detail/31989.htm)<br>
  1383. - url {String} After a file is uploaded successfully, the OSS sends a callback request to this URL.
  1384. - [host] {String} The host header value for initiating callback requests.
  1385. - body {String} The value of the request body when a callback is initiated, for example, key=${key}&etag=${etag}&my_var=${x:my_var}.
  1386. - [contentType] {String} The Content-Type of the callback requests initiatiated, It supports application/x-www-form-urlencoded and application/json, and the former is the default value.
  1387. - [callbackSNI] {Boolean} Specifies whether OSS sends Server Name Indication (SNI) to the origin address specified by callbackUrl when a callback request is initiated from the client.
  1388. - [customValue] {Object} Custom parameters are a map of key-values<br>
  1389. e.g.:
  1390. ```js
  1391. var customValue = { var1: 'value1', var2: 'value2' };
  1392. ```
  1393. - [headers] {Object} extra headers, detail see [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616.html)
  1394. - 'Cache-Control' cache control for download, e.g.: `Cache-Control: public, no-cache`
  1395. - 'Content-Disposition' object name for download, e.g.: `Content-Disposition: somename`
  1396. - 'Content-Encoding' object content encoding for download, e.g.: `Content-Encoding: gzip`
  1397. - 'Expires' expires time for download, an absolute date and time. e.g.: `Tue, 08 Dec 2020 13:49:43 GMT`
  1398. Success will return the object information.
  1399. object:
  1400. - name {String} object name
  1401. - res {Object} response info, including
  1402. - status {Number} response status
  1403. - headers {Object} response headers
  1404. - size {Number} response size
  1405. - rt {Number} request total use time (ms)
  1406. example:
  1407. - Add an object through readstream
  1408. ```js
  1409. const filepath = '/home/ossdemo/demo.txt';
  1410. store.putStream('ossdemo/readstream.txt', fs.createReadStream(filepath)).then((result) => {
  1411. console.log(result);
  1412. });
  1413. // {
  1414. // name: 'ossdemo/readstream.txt',
  1415. // url: 'http://demo.oss-cn-hangzhou.aliyuncs.com/ossdemo/readstream.txt',
  1416. // res: {
  1417. // status: 200,
  1418. // headers: {
  1419. // date: 'Tue, 17 Feb 2015 13:28:17 GMT',
  1420. // 'content-length': '0',
  1421. // connection: 'close',
  1422. // etag: '"BF7A03DA01440845BC5D487B369BC168"',
  1423. // server: 'AliyunOSS',
  1424. // 'x-oss-request-id': '54E341F1707AA0275E829242'
  1425. // },
  1426. // size: 0,
  1427. // rt: 92
  1428. // }
  1429. // }
  1430. ```
  1431. ### .append(name, file[, options])
  1432. Append an object to the bucket, it's almost same as put, but it can add content to existing object rather than override it.
  1433. All parameters are same as put except for options.position
  1434. - name {String} object name store on OSS
  1435. - file {String|Buffer|ReadStream} object local path, content buffer or ReadStream content instance
  1436. - [options] {Object} optional parameters
  1437. - [position] {String} specify the position which is the content length of the latest object
  1438. - [timeout] {Number} the operation timeout
  1439. - [mime] {String} custom mime, will send with `Content-Type` entity header
  1440. - [meta] {Object} user meta, will send with `x-oss-meta-` prefix string
  1441. e.g.: `{ uid: 123, pid: 110 }`
  1442. - [headers] {Object} extra headers, detail see [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616.html)
  1443. - 'Cache-Control' cache control for download, e.g.: `Cache-Control: public, no-cache`
  1444. - 'Content-Disposition' object name for download, e.g.: `Content-Disposition: somename`
  1445. - 'Content-Encoding' object content encoding for download, e.g.: `Content-Encoding: gzip`
  1446. - 'Expires' expires time for download, an absolute date and time. e.g.: `Tue, 08 Dec 2020 13:49:43 GMT`
  1447. object:
  1448. - name {String} object name
  1449. - url {String} the url of oss
  1450. - res {Object} response info, including
  1451. - status {Number} response status
  1452. - headers {Object} response headers
  1453. - size {Number} response size
  1454. - rt {Number} request total use time (ms)
  1455. - nextAppendPosition {String} the next position(The browser needs to set cross domain and expose the x-oss-next-append-position header)
  1456. example:
  1457. ```js
  1458. let object = await store.append('ossdemo/buffer', Buffer.from('foo'));
  1459. // append content to the existing object
  1460. object = await store.append('ossdemo/buffer', Buffer.from('bar'), {
  1461. position: object.nextAppendPosition
  1462. });
  1463. ```
  1464. ### .getObjectUrl(name[, baseUrl])
  1465. Get the Object url.
  1466. If provide `baseUrl`, will use `baseUrl` instead the default `endpoint`.
  1467. e.g.:
  1468. ```js
  1469. const cdnUrl = store.getObjectUrl('foo/bar.jpg', 'https://mycdn.domian.com');
  1470. // cdnUrl should be `https://mycdn.domian.com/foo/bar.jpg`
  1471. ```
  1472. ### .generateObjectUrl(name[, baseUrl])
  1473. Get the Object url.
  1474. If provide `baseUrl`, will use `baseUrl` instead the default `bucket and endpoint `.
  1475. Suggest use generateObjectUrl instead of getObjectUrl.
  1476. e.g.:
  1477. ```js
  1478. const url = store.generateObjectUrl('foo/bar.jpg');
  1479. // cdnUrl should be `https://${bucketname}.${endpotint}foo/bar.jpg`
  1480. const cdnUrl = store.generateObjectUrl('foo/bar.jpg', 'https://mycdn.domian.com');
  1481. // cdnUrl should be `https://mycdn.domian.com/foo/bar.jpg`
  1482. ```
  1483. ### .head(name[, options])
  1484. Head an object and get the meta info.
  1485. parameters:
  1486. - name {String} object name store on OSS
  1487. - [options] {Object} optional parameters
  1488. - [timeout] {Number} the operation timeout
  1489. - [versionId] {String} the version id of history object
  1490. - [headers] {Object} extra headers, detail see [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616.html)
  1491. - 'If-Modified-Since' object modified after this time will return 200 and object meta,
  1492. otherwise return 304 not modified
  1493. - 'If-Unmodified-Since' object modified before this time will return 200 and object meta,
  1494. otherwise throw PreconditionFailedError
  1495. - 'If-Match' object etag equal this will return 200 and object meta,
  1496. otherwise throw PreconditionFailedError
  1497. - 'If-None-Match' object etag not equal this will return 200 and object meta,
  1498. otherwise return 304 not modified
  1499. Success will return the object's meta information.
  1500. object:
  1501. - status {Number} response status, maybe 200 or 304
  1502. - meta {Object} object user meta, if not set on `put()`, will return null.
  1503. If return status 304, meta will be null too
  1504. - res {Object} response info, including
  1505. - status {Number} response status
  1506. - headers {Object} response headers
  1507. - [x-oss-version-id] return in multiversion
  1508. - size {Number} response size
  1509. - rt {Number} request total use time (ms)
  1510. example:
  1511. - Head an exists object and get user meta
  1512. ```js
  1513. await this.store.put('ossdemo/head-meta', Buffer.from('foo'), {
  1514. meta: {
  1515. uid: 1,
  1516. path: 'foo/demo.txt'
  1517. }
  1518. });
  1519. const object = await this.store.head('ossdemo/head-meta');
  1520. console.log(object);
  1521. // {
  1522. // status: 200,
  1523. // meta: {
  1524. // uid: '1',
  1525. // path: 'foo/demo.txt'
  1526. // },
  1527. // res: { ... }
  1528. // }
  1529. ```
  1530. - Head a not exists object
  1531. ```js
  1532. const object = await this.store.head('ossdemo/head-meta');
  1533. // will throw NoSuchKeyError
  1534. ```
  1535. ### .getObjectMeta(name[, options])
  1536. Get an object meta info include ETag、Size、LastModified and so on, not return object content.
  1537. parameters:
  1538. - name {String} object name store on OSS
  1539. - [options] {Object} optional parameters
  1540. - [timeout] {Number} the operation timeout
  1541. - [versionId] {String} the version id of history object
  1542. Success will return the object's meta information.
  1543. object:
  1544. - status {Number} response status
  1545. - res {Object} response info, including
  1546. - headers {Object} response headers
  1547. example:
  1548. - Head an exists object and get object meta info
  1549. ```js
  1550. await this.store.put('ossdemo/object-meta', Buffer.from('foo'));
  1551. const object = await this.store.getObjectMeta('ossdemo/object-meta');
  1552. console.log(object);
  1553. // {
  1554. // status: 200,
  1555. // res: { ... }
  1556. // }
  1557. ```
  1558. ### .get(name[, file, options])
  1559. Get an object from the bucket.
  1560. parameters:
  1561. - name {String} object name store on OSS
  1562. - [file] {String|WriteStream|Object} file path or WriteStream instance to store the content
  1563. If `file` is null or ignore this parameter, function will return info contains `content` property.
  1564. If `file` is Object, it will be treated as options.
  1565. - [options] {Object} optional parameters
  1566. - [versionId] {String} the version id of history object
  1567. - [timeout] {Number} the operation timeout
  1568. - [process] {String} image process params, will send with `x-oss-process`
  1569. e.g.: `{process: 'image/resize,w_200'}`
  1570. - [responseCacheControl] {String} default `no-cache`, (only support Browser). response-cache-control, will response with HTTP Header `Cache-Control`
  1571. - [headers] {Object} extra headers, detail see [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616.html)
  1572. - 'Range' get specifying range bytes content, e.g.: `Range: bytes=0-9`
  1573. - 'If-Modified-Since' object modified after this time will return 200 and object meta,
  1574. otherwise return 304 not modified
  1575. - 'If-Unmodified-Since' object modified before this time will return 200 and object meta,
  1576. otherwise throw PreconditionFailedError
  1577. - 'If-Match' object etag equal this will return 200 and object meta,
  1578. otherwise throw PreconditionFailedError
  1579. - 'If-None-Match' object etag not equal this will return 200 and object meta,
  1580. otherwise return 304 not modified
  1581. Success will return the info contains response.
  1582. object:
  1583. - [content] {Buffer} file content buffer if `file` parameter is null or ignore
  1584. - res {Object} response info, including
  1585. - status {Number} response status
  1586. - headers {Object} response headers
  1587. - size {Number} response size
  1588. - rt {Number} request total use time (ms)
  1589. If object not exists, will throw NoSuchKeyError.
  1590. example:
  1591. - Get an exists object and store it to the local file
  1592. ```js
  1593. const filepath = '/home/ossdemo/demo.txt';
  1594. await store.get('ossdemo/demo.txt', filepath);
  1595. ```
  1596. \_ Store object to a writestream
  1597. ```js
  1598. await store.get('ossdemo/demo.txt', somestream);
  1599. ```
  1600. - Get an object content buffer
  1601. ```js
  1602. const result = await store.get('ossdemo/demo.txt');
  1603. console.log(Buffer.isBuffer(result.content));
  1604. ```
  1605. - Get a processed image and store it to the local file
  1606. ```js
  1607. const filepath = '/home/ossdemo/demo.png';
  1608. await store.get('ossdemo/demo.png', filepath, { process: 'image/resize,w_200' });
  1609. ```
  1610. - Get a not exists object
  1611. ```js
  1612. const filepath = '/home/ossdemo/demo.txt';
  1613. await store.get('ossdemo/not-exists-demo.txt', filepath);
  1614. // will throw NoSuchKeyError
  1615. ```
  1616. - Get a historic version object
  1617. ```js
  1618. const filepath = '/home/ossdemo/demo.txt';
  1619. const versionId = 'versionId string';
  1620. await store.get('ossdemo/not-exists-demo.txt', filepath, {
  1621. versionId
  1622. });
  1623. ```
  1624. - If `file` is Object, it will be treated as options.
  1625. ```js
  1626. const versionId = 'versionId string';
  1627. await store.get('ossdemo/not-exists-demo.txt', { versionId });
  1628. ```
  1629. ### .getStream(name[, options])
  1630. Get an object read stream.
  1631. parameters:
  1632. - name {String} object name store on OSS
  1633. - [options] {Object} optional parameters
  1634. - [timeout] {Number} the operation timeout
  1635. - [process] {String} image process params, will send with `x-oss-process`
  1636. - [headers] {Object} extra headers
  1637. - 'If-Modified-Since' object modified after this time will return 200 and object meta,
  1638. otherwise return 304 not modified
  1639. - 'If-Unmodified-Since' object modified before this time will return 200 and object meta,
  1640. otherwise throw PreconditionFailedError
  1641. - 'If-Match' object etag equal this will return 200 and object meta,
  1642. otherwise throw PreconditionFailedError
  1643. - 'If-None-Match' object etag not equal this will return 200 and object meta,
  1644. otherwise return 304 not modified
  1645. Success will return the stream instance and response info.
  1646. object:
  1647. - stream {ReadStream} readable stream instance. If response status is not `200`, stream will be `null`.
  1648. - res {Object} response info, including
  1649. - status {Number} response status
  1650. - headers {Object} response headers
  1651. - size {Number} response size
  1652. - rt {Number} request total use time (ms)
  1653. If object not exists, will throw NoSuchKeyError.
  1654. example:
  1655. - Get an exists object stream
  1656. ```js
  1657. const result = await store.getStream('ossdemo/demo.txt');
  1658. result.stream.pipe(fs.createWriteStream('some file.txt'));
  1659. ```
  1660. ### .delete(name[, options])
  1661. Delete an object from the bucket.
  1662. parameters:
  1663. - name {String} object name store on OSS
  1664. - [options] {Object} optional parameters
  1665. - [timeout] {Number} the operation timeout
  1666. - [versionId] {String} the version id of history object
  1667. Success will return the info contains response.
  1668. object:
  1669. - res {Object} response info, including
  1670. - status {Number} response status
  1671. - headers {Object} response headers
  1672. - size {Number} response size
  1673. - rt {Number} request total use time (ms)
  1674. If delete object not exists, will also delete success.
  1675. example:
  1676. - Delete an exists object
  1677. ```js
  1678. await store.delete('ossdemo/someobject');
  1679. ```
  1680. - Delete a not exists object
  1681. ```js
  1682. await store.delete('ossdemo/some-not-exists-object');
  1683. ```
  1684. - Delete a history object or deleteMarker
  1685. ```js
  1686. const versionId = 'versionId';
  1687. await store.delete('ossdemo/some-not-exists-object', { versionId });
  1688. ```
  1689. ### .copy(name, sourceName[, sourceBucket, options])
  1690. Copy an object from `sourceName` to `name`.
  1691. parameters:
  1692. - name {String} object name store on OSS
  1693. - sourceName {String} source object name
  1694. - [sourceBucket] {String} source Bucket. if doesn't exist,`sourceBucket` is same bucket.
  1695. - [options] {Object} optional parameters
  1696. - [versionId] {String} the version id of history object
  1697. - [timeout] {Number} the operation timeout
  1698. - [meta] {Object} user meta, will send with `x-oss-meta-` prefix string
  1699. e.g.: `{ uid: 123, pid: 110 }`
  1700. If the `meta` set, will override the source object meta.
  1701. - [headers] {Object} extra headers
  1702. - 'If-Match' do copy if source object etag equal this,
  1703. otherwise throw PreconditionFailedError
  1704. - 'If-None-Match' do copy if source object etag not equal this,
  1705. otherwise throw PreconditionFailedError
  1706. - 'If-Modified-Since' do copy if source object modified after this time,
  1707. otherwise throw PreconditionFailedError
  1708. - 'If-Unmodified-Since' do copy if source object modified before this time,
  1709. otherwise throw PreconditionFailedError
  1710. - See more: [CopyObject](https://help.aliyun.com/document_detail/31979.html?#title-tzy-vxc-ncx)
  1711. Success will return the copy result in `data` property.
  1712. object:
  1713. - data {Object} copy result
  1714. - lastModified {String} object last modified GMT string
  1715. - etag {String} object etag contains `"`, e.g.: `"5B3C1A2E053D763E1B002CC607C5A0FE"`
  1716. - res {Object} response info, including
  1717. - status {Number} response status
  1718. - headers {Object} response headers
  1719. - size {Number} response size
  1720. - rt {Number} request total use time (ms)
  1721. If source object not exists, will throw NoSuchKeyError.
  1722. example:
  1723. - Copy same bucket object
  1724. ```js
  1725. store.copy('newName', 'oldName').then(result => {
  1726. console.log(result);
  1727. });
  1728. ```
  1729. - Copy other bucket object
  1730. ```js
  1731. store.copy('logo.png', 'logo.png', 'other-bucket').then(result => {
  1732. console.log(result);
  1733. });
  1734. ```
  1735. - Copy historic object
  1736. ```js
  1737. const versionId = 'your verisonId';
  1738. store.copy('logo.png', 'logo.png', 'other-bucket', { versionId }).then(result => {
  1739. console.log(result);
  1740. });
  1741. ```
  1742. ### .putMeta(name, meta[, options])
  1743. Set an exists object meta.
  1744. parameters:
  1745. - name {String} object name store on OSS
  1746. - meta {Object} user meta, will send with `x-oss-meta-` prefix string
  1747. e.g.: `{ uid: 123, pid: 110 }`
  1748. If `meta: null`, will clean up the exists meta
  1749. - [options] {Object} optional parameters
  1750. - [timeout] {Number} the operation timeout
  1751. Success will return the putMeta result in `data` property.
  1752. - data {Object} copy result
  1753. - lastModified {String} object last modified GMT date, e.g.: `2015-02-19T08:39:44.000Z`
  1754. - etag {String} object etag contains `"`, e.g.: `"5B3C1A2E053D763E1B002CC607C5A0FE"`
  1755. - res {Object} response info, including
  1756. - status {Number} response status
  1757. - headers {Object} response headers
  1758. - size {Number} response size
  1759. - rt {Number} request total use time (ms)
  1760. If object not exists, will throw NoSuchKeyError.
  1761. example:
  1762. - Update exists object meta
  1763. ```js
  1764. const result = await store.putMeta('ossdemo.txt', {
  1765. uid: 1,
  1766. pid: 'p123'
  1767. });
  1768. console.log(result);
  1769. ```
  1770. - Clean up object meta
  1771. ```js
  1772. await store.putMeta('ossdemo.txt', null);
  1773. ```
  1774. ### .deleteMulti(names[, options])
  1775. Delete multi objects in one request.
  1776. parameters:
  1777. - names {Array<Object>} object names, max 1000 objects in once.
  1778. - key {String} object name
  1779. - [versionId] {String} the version id of history object or deleteMarker
  1780. - [options] {Object} optional parameters
  1781. - [quiet] {Boolean} quiet mode or verbose mode, default is `false`, verbose mode
  1782. quiet mode: if all objects delete succes, return emtpy response.
  1783. otherwise return delete error object results.
  1784. verbose mode: return all object delete results.
  1785. - [timeout] {Number} the operation timeout
  1786. Success will return delete success objects in `deleted` property.
  1787. - [deleted] {Array<Object>} deleted object or deleteMarker info list
  1788. - [Key] {String} object name
  1789. - [VersionId] {String} object versionId
  1790. - [DeleteMarker] {String} generate or delete marker
  1791. - [DeleteMarkerVersionId] {String} marker versionId
  1792. - res {Object} response info, including
  1793. - status {Number} response status
  1794. - headers {Object} response headers
  1795. - size {Number} response size
  1796. - rt {Number} request total use time (ms)
  1797. example:
  1798. - Delete multi objects in quiet mode
  1799. ```js
  1800. const result = await store.deleteMulti(['obj1', 'obj2', 'obj3'], {
  1801. quiet: true
  1802. });
  1803. ```
  1804. - Delete multi objects in verbose mode
  1805. ```js
  1806. const result = await store.deleteMulti(['obj1', 'obj2', 'obj3']);
  1807. ```
  1808. - Delete multi objects in multiversion
  1809. ```js
  1810. const obj1 = {
  1811. key: 'key1',
  1812. versionId: 'versionId1'
  1813. };
  1814. const obj2 = {
  1815. key: 'key2',
  1816. versionId: 'versionId2'
  1817. };
  1818. const result = await store.deleteMulti([obj1, obj2]);
  1819. ```
  1820. ### .list(query[, options])
  1821. List objects in the bucket.
  1822. parameters:
  1823. - [query] {Object} query parameters, default is `null`
  1824. - [prefix] {String} search object using `prefix` key
  1825. - [marker] {String} search start from `marker`, including `marker` key
  1826. - [delimiter] {String} delimiter search scope
  1827. e.g. `/` only search current dir, not including subdir
  1828. - [max-keys] {String|Number} max objects, default is `100`, limit to `1000`
  1829. - [options] {Object} optional parameters
  1830. - [timeout] {Number} the operation timeout
  1831. Success will return objects list on `objects` properties.
  1832. - objects {Array<ObjectMeta>} object meta info list
  1833. Each `ObjectMeta` will contains blow properties:
  1834. - name {String} object name on oss
  1835. - lastModified {String} object last modified GMT date, e.g.: `2015-02-19T08:39:44.000Z`
  1836. - etag {String} object etag contains `"`, e.g.: `"5B3C1A2E053D763E1B002CC607C5A0FE"`
  1837. - type {String} object type, e.g.: `Normal`
  1838. - size {Number} object size, e.g.: `344606`
  1839. - storageClass {String} storage class type, e.g.: `Standard`
  1840. - owner {Object} object owner, including `id` and `displayName`
  1841. - prefixes {Array<String>} prefix list
  1842. - isTruncated {Boolean} truncate or not
  1843. - nextMarker {String} next marker string
  1844. - res {Object} response info, including
  1845. - status {Number} response status
  1846. - headers {Object} response headers
  1847. - size {Number} response size
  1848. - rt {Number} request total use time (ms)
  1849. example:
  1850. - List top 10 objects
  1851. ```js
  1852. const result = await store.list();
  1853. console.log(result.objects);
  1854. ```
  1855. - List `fun/` dir including subdirs objects
  1856. ```js
  1857. const result = await store.list({
  1858. prefix: 'fun/'
  1859. });
  1860. console.log(result.objects);
  1861. ```
  1862. - List `fun/` dir objects, not including subdirs
  1863. ```js
  1864. const result = await store.list({
  1865. prefix: 'fun/',
  1866. delimiter: '/'
  1867. });
  1868. console.log(result.objects);
  1869. ```
  1870. ### .listV2(query[, options])
  1871. List objects in the bucket.(recommended)
  1872. parameters:
  1873. - [query] {Object} query parameters, default is `null`
  1874. - [prefix] {String} search object using `prefix` key
  1875. - [continuation-token] (continuationToken) {String} search start from `continuationToken`, including `continuationToken` key
  1876. - [delimiter] {String} delimiter search scope
  1877. e.g. `/` only search current dir, not including subdir
  1878. - [max-keys] {String|Number} max objects, default is `100`, limit to `1000`
  1879. - [start-after] {String} specifies the Start-after value from which to start the list. The names of objects are returned in alphabetical order.
  1880. - [fetch-owner] {Boolean} specifies whether to include the owner information in the response.
  1881. - [options] {Object} optional parameters
  1882. - [timeout] {Number} the operation timeout
  1883. Success will return objects list on `objects` properties.
  1884. - objects {Array<ObjectMeta>} object meta info list
  1885. Each `ObjectMeta` will contains blow properties:
  1886. - name {String} object name on oss
  1887. - url {String} resource url
  1888. - lastModified {String} object last modified GMT date, e.g.: `2015-02-19T08:39:44.000Z`
  1889. - etag {String} object etag contains `"`, e.g.: `"5B3C1A2E053D763E1B002CC607C5A0FE"`
  1890. - type {String} object type, e.g.: `Normal`
  1891. - size {Number} object size, e.g.: `344606`
  1892. - storageClass {String} storage class type, e.g.: `Standard`
  1893. - owner {Object|null} object owner, including `id` and `displayName`
  1894. - prefixes {Array<String>} prefix list
  1895. - isTruncated {Boolean} truncate or not
  1896. - nextContinuationToken {String} next continuation-token string
  1897. - keyCount {Number} The number of keys returned for this request. If Delimiter is specified, KeyCount is the sum of the elements in Key and CommonPrefixes.
  1898. - res {Object} response info, including
  1899. - status {Number} response status
  1900. - headers {Object} response headers
  1901. - size {Number} response size
  1902. - rt {Number} request total use time (ms)
  1903. - List top 10 objects
  1904. ```js
  1905. const result = await store.listV2({
  1906. 'max-keys': 10
  1907. });
  1908. console.log(result.objects);
  1909. ```
  1910. - List `fun/` dir including subdirs objects
  1911. ```js
  1912. const result = await store.listV2({
  1913. prefix: 'fun/'
  1914. });
  1915. console.log(result.objects);
  1916. ```
  1917. - List `fun/` dir objects, not including subdirs
  1918. ```js
  1919. const result = await store.listV2({
  1920. prefix: 'fun/',
  1921. delimiter: '/'
  1922. });
  1923. console.log(result.objects);
  1924. ```
  1925. - List `a/` dir objects, after `a/b` and not include `a/b`
  1926. ```js
  1927. const result = await store.listV2({
  1928. delimiter: '/',
  1929. prefix: 'a/',
  1930. 'start-after': 'a/b'
  1931. });
  1932. console.log(result.objects);
  1933. ```
  1934. ### .getBucketVersions(query[, options])
  1935. List the version information of all objects in the bucket, including the delete marker (Delete Marker).
  1936. parameters:
  1937. - [query] {Object} query parameters, default is `null`
  1938. - [prefix] {String} search object using `prefix` key
  1939. - [versionIdMarker] {String} set the result to return from the version ID marker of the key marker object and sort by the versions
  1940. - [keyMarker] {String} search start from `keyMarker`, including `keyMarker` key
  1941. - [encodingType] {String} specifies that the returned content is encoded, and specifies the type of encoding
  1942. - [delimiter] {String} delimiter search scope
  1943. e.g. `/` only search current dir, not including subdir
  1944. - [maxKeys] {String|Number} max objects, default is `100`, limit to `1000`
  1945. - [options] {Object} optional parameters
  1946. - [timeout] {Number} the operation timeout
  1947. Success will return objects list on `objects` properties.
  1948. - objects {Array<ObjectMeta>} object meta info list
  1949. Each `ObjectMeta` will contains blow properties:
  1950. - name {String} object name on oss
  1951. - lastModified {String} object last modified GMT date, e.g.: `2015-02-19T08:39:44.000Z`
  1952. - etag {String} object etag contains `"`, e.g.: `"5B3C1A2E053D763E1B002CC607C5A0FE"`
  1953. - type {String} object type, e.g.: `Normal`
  1954. - size {Number} object size, e.g.: `344606`
  1955. - isLatest {Boolean}
  1956. - versionId {String} object versionId
  1957. - storageClass {String} storage class type, e.g.: `Standard`
  1958. - owner {Object} object owner, including `id` and `displayName`
  1959. - deleteMarker {Array<ObjectDeleteMarker>} object delete marker info list
  1960. Each `ObjectDeleteMarker`
  1961. - name {String} object name on oss
  1962. - lastModified {String} object last modified GMT date, e.g.: `2015-02-19T08:39:44.000Z`
  1963. - versionId {String} object versionId
  1964. - isTruncated {Boolean} truncate or not
  1965. - nextKeyMarker (nextMarker) {String} next marker string
  1966. - nextVersionIdMarker (NextVersionIdMarker) {String} next version ID marker string
  1967. - res {Object} response info, including
  1968. - status {Number} response status
  1969. - headers {Object} response headers
  1970. - size {Number} response size
  1971. - rt {Number} request total use time (ms)
  1972. example:
  1973. - View all versions of objects and deleteMarker of bucket
  1974. ```js
  1975. const result = await store.getBucketVersions();
  1976. console.log(result.objects);
  1977. console.log(result.deleteMarker);
  1978. ```
  1979. - List from key-marker
  1980. ```js
  1981. const result = await store.getBucketVersions({
  1982. keyMarker: 'keyMarker'
  1983. });
  1984. console.log(result.objects);
  1985. ```
  1986. - List from the version-id-marker of key-marker
  1987. ```js
  1988. const result = await store.getBucketVersions({
  1989. versionIdMarker: 'versionIdMarker',
  1990. keyMarker: 'keyMarker'
  1991. });
  1992. console.log(result.objects);
  1993. console.log(result.deleteMarker);
  1994. ```
  1995. ### .signatureUrl(name[, options, strictObjectNameValidation])
  1996. Create a signature url for download or upload object. When you put object with signatureUrl ,you need to pass `Content-Type`.Please look at the example.
  1997. parameters:
  1998. - name {String} object name store on OSS
  1999. - [options] {Object} optional parameters
  2000. - [expires] {Number} after expires seconds, the url will become invalid, default is `1800`
  2001. - [method] {String} the HTTP method, default is 'GET'
  2002. - [Content-Type] {String} set the request content type
  2003. - [process] {String} image process params, will send with `x-oss-process`
  2004. e.g.: `{process: 'image/resize,w_200'}`
  2005. - [trafficLimit] {Number} traffic limit, range: `819200`~`838860800`.
  2006. - [subResource] {Object} additional signature parameters in url.
  2007. - [response] {Object} set the response headers for download
  2008. - [content-type] {String} set the response content type
  2009. - [content-disposition] {String} set the response content disposition
  2010. - [cache-control] {String} set the response cache control
  2011. - See more: <https://help.aliyun.com/document_detail/31980.html>
  2012. - [callback] {Object} set the callback for the operation
  2013. - url {String} set the url for callback
  2014. - [host] {String} set the host for callback
  2015. - body {String} set the body for callback
  2016. - [contentType] {String} set the type for body
  2017. - [callbackSNI] {Boolean} Specifies whether OSS sends Server Name Indication (SNI) to the origin address specified by callbackUrl when a callback request is initiated from the client
  2018. - [customValue] {Object} set the custom value for callback,eg. {var1: value1,var2:value2}
  2019. - [strictObjectNameValidation] {boolean} the flag of verifying object name strictly, default is true
  2020. Success will return signature url.
  2021. example:
  2022. - Get signature url for object
  2023. ```js
  2024. const url = store.signatureUrl('ossdemo.txt');
  2025. console.log(url);
  2026. // --------------------------------------------------
  2027. const url = store.signatureUrl('ossdemo.txt', {
  2028. expires: 3600,
  2029. method: 'PUT'
  2030. });
  2031. console.log(url);
  2032. // put object with signatureUrl
  2033. // -------------------------------------------------
  2034. const url = store.signatureUrl('ossdemo.txt', {
  2035. expires: 3600,
  2036. method: 'PUT',
  2037. 'Content-Type': 'text/plain; charset=UTF-8'
  2038. });
  2039. console.log(url);
  2040. // --------------------------------------------------
  2041. const url = store.signatureUrl(
  2042. 'ossdemo.txt',
  2043. {
  2044. expires: 3600,
  2045. response: {
  2046. 'content-type': 'text/custom',
  2047. 'content-disposition': 'attachment'
  2048. }
  2049. },
  2050. false
  2051. );
  2052. console.log(url);
  2053. // put operation
  2054. ```
  2055. - Get a signature url for a processed image
  2056. ```js
  2057. const url = store.signatureUrl('ossdemo.png', {
  2058. process: 'image/resize,w_200'
  2059. });
  2060. console.log(url);
  2061. // --------------------------------------------------
  2062. const url = store.signatureUrl('ossdemo.png', {
  2063. expires: 3600,
  2064. process: 'image/resize,w_200'
  2065. });
  2066. console.log(url);
  2067. ```
  2068. ### .asyncSignatureUrl(name[, options, strictObjectNameValidation])
  2069. Basically the same as signatureUrl, if refreshSTSToken is configured asyncSignatureUrl will refresh stsToken
  2070. parameters:
  2071. - name {String} object name store on OSS
  2072. - [options] {Object} optional parameters
  2073. - [expires] {Number} after expires seconds, the url will become invalid, default is `1800`
  2074. - [method] {String} the HTTP method, default is 'GET'
  2075. - [Content-Type] {String} set the request content type
  2076. - [process] {String} image process params, will send with `x-oss-process`
  2077. e.g.: `{process: 'image/resize,w_200'}`
  2078. - [trafficLimit] {Number} traffic limit, range: `819200`~`838860800`.
  2079. - [subResource] {Object} additional signature parameters in url.
  2080. - [response] {Object} set the response headers for download
  2081. - [content-type] {String} set the response content type
  2082. - [content-disposition] {String} set the response content disposition
  2083. - [cache-control] {String} set the response cache control
  2084. - See more: <https://help.aliyun.com/document_detail/31980.html>
  2085. - [callback] {Object} set the callback for the operation
  2086. - url {String} set the url for callback
  2087. - [host] {String} set the host for callback
  2088. - body {String} set the body for callback
  2089. - [contentType] {String} set the type for body
  2090. - [callbackSNI] {Boolean} Specifies whether OSS sends Server Name Indication (SNI) to the origin address specified by callbackUrl when a callback request is initiated from the client
  2091. - [customValue] {Object} set the custom value for callback,eg. {var1: value1,var2:value2}
  2092. - [strictObjectNameValidation] {boolean} the flag of verifying object name strictly, default is true
  2093. Success will return signature url.
  2094. example:
  2095. - Get signature url for object
  2096. ```js
  2097. const url = await store.asyncSignatureUrl('ossdemo.txt');
  2098. console.log(url);
  2099. // --------------------------------------------------
  2100. const url = await store.asyncSignatureUrl('ossdemo.txt', {
  2101. expires: 3600,
  2102. method: 'PUT'
  2103. });
  2104. console.log(url);
  2105. // put object with signatureUrl
  2106. // -------------------------------------------------
  2107. const url = await store.asyncSignatureUrl('ossdemo.txt', {
  2108. expires: 3600,
  2109. method: 'PUT',
  2110. 'Content-Type': 'text/plain; charset=UTF-8'
  2111. });
  2112. console.log(url);
  2113. // --------------------------------------------------
  2114. const url = await store.asyncSignatureUrl(
  2115. 'ossdemo.txt',
  2116. {
  2117. expires: 3600,
  2118. response: {
  2119. 'content-type': 'text/custom',
  2120. 'content-disposition': 'attachment'
  2121. }
  2122. },
  2123. false
  2124. );
  2125. console.log(url);
  2126. // put operation
  2127. ```
  2128. - Get a signature url for a processed image
  2129. ```js
  2130. const url = await store.asyncSignatureUrl('ossdemo.png', {
  2131. process: 'image/resize,w_200'
  2132. });
  2133. console.log(url);
  2134. // --------------------------------------------------
  2135. const url = await store.asyncSignatureUrl('ossdemo.png', {
  2136. expires: 3600,
  2137. process: 'image/resize,w_200'
  2138. });
  2139. console.log(url);
  2140. ```
  2141. ### .signatureUrlV4(method, expires[, request, objectName, additionalHeaders])
  2142. Generate a signed URL for V4 of an OSS resource and share the URL to allow authorized third-party users to access the resource.
  2143. parameters:
  2144. - method {string} the HTTP method
  2145. - expires {number} the signed URL will expire after the set number of seconds
  2146. - [request] {Object} optional request parameters
  2147. - [headers] {Object} headers of http requests, please make sure these request headers are set during the actual request
  2148. - [queries] {Object} queries of the signed URL, please ensure that if the query only has key, the value is set to null
  2149. - [objectName] {string} object name
  2150. - [additionalHeaders] {string[]} the keys of the request headers that need to be calculated into the V4 signature, please ensure that these additional headers are included in the request headers
  2151. Success will return signature url.
  2152. example:
  2153. ```js
  2154. // GetObject
  2155. const getObjectUrl = await store.signatureUrlV4('GET', 60, undefined, 'your obejct name');
  2156. console.log(getObjectUrl);
  2157. // --------------------------------------------------
  2158. const getObjectUrl = await store.signatureUrlV4(
  2159. 'GET',
  2160. 60,
  2161. {
  2162. headers: {
  2163. 'Cache-Control': 'no-cache'
  2164. },
  2165. queries: {
  2166. versionId: 'version ID of your object'
  2167. }
  2168. },
  2169. 'your obejct name',
  2170. ['Cache-Control']
  2171. );
  2172. console.log(getObjectUrl);
  2173. // -------------------------------------------------
  2174. // PutObject
  2175. const putObejctUrl = await store.signatureUrlV4('PUT', 60, undefined, 'your obejct name');
  2176. console.log(putObejctUrl);
  2177. // --------------------------------------------------
  2178. const putObejctUrl = await store.signatureUrlV4(
  2179. 'PUT',
  2180. 60,
  2181. {
  2182. headers: {
  2183. 'Content-Type': 'text/plain',
  2184. 'Content-MD5': 'xxx',
  2185. 'Content-Length': 1
  2186. }
  2187. },
  2188. 'your obejct name',
  2189. ['Content-Length']
  2190. );
  2191. console.log(putObejctUrl);
  2192. ```
  2193. ### .putACL(name, acl[, options])
  2194. Set object's ACL.
  2195. parameters:
  2196. - name {String} object name
  2197. - acl {String} acl (private/public-read/public-read-write)
  2198. - [options] {Object} optional parameters
  2199. - [timeout] {Number} the operation timeout
  2200. - [versionId] {String} the version id of history object
  2201. Success will return:
  2202. - res {Object} response info, including
  2203. - status {Number} response status
  2204. - headers {Object} response headers
  2205. - size {Number} response size
  2206. - rt {Number} request total use time (ms)
  2207. example:
  2208. - Set an object's ACL
  2209. ```js
  2210. await store.putACL('ossdemo.txt', 'public-read');
  2211. ```
  2212. - Set an history object's ACL
  2213. ```js
  2214. const versionId = 'object versionId';
  2215. await store.putACL('ossdemo.txt', 'public-read', {
  2216. versionId
  2217. });
  2218. ```
  2219. ### .getACL(name[, options])
  2220. Get object's ACL.
  2221. parameters:
  2222. - name {String} object name
  2223. - [options] {Object} optional parameters
  2224. - [timeout] {Number} the operation timeout
  2225. - [versionId] {String} the version id of history object
  2226. Success will return:
  2227. - acl {String} acl settiongs string
  2228. - res {Object} response info, including
  2229. - status {Number} response status
  2230. - headers {Object} response headers
  2231. - size {Number} response size
  2232. - rt {Number} request total use time (ms)
  2233. example:
  2234. - Get an object's ACL
  2235. ```js
  2236. const result = await store.getACL('ossdemo.txt');
  2237. console.log(result.acl);
  2238. ```
  2239. - Get an history object's ACL
  2240. ```js
  2241. const versionId = 'object versionId';
  2242. const result = await store.getACL('ossdemo.txt', { versionId });
  2243. console.log(result.acl);
  2244. ```
  2245. ### .restore(name[, options])
  2246. Restore Object.
  2247. parameters:
  2248. - name {String} object name
  2249. - [options] {Object} optional parameters
  2250. - [timeout] {Number} the operation timeout
  2251. - [versionId] {String} the version id of history object
  2252. - [type] {String} the default type is Archive
  2253. Success will return:
  2254. - res {Object} response info, including
  2255. - status {Number} response status
  2256. - headers {Object} response headers
  2257. - size {Number} response size
  2258. - rt {Number} request total use time (ms)
  2259. example:
  2260. - Restore an object with Archive type
  2261. ```js
  2262. const result = await store.restore('ossdemo.txt');
  2263. console.log(result.status);
  2264. ```
  2265. - Restore an object with ColdArchive type
  2266. ```js
  2267. const result = await store.restore('ossdemo.txt', { type: 'ColdArchive' });
  2268. console.log(result.status);
  2269. ```
  2270. - Days for unfreezing Specifies the days for unfreezing
  2271. ```js
  2272. const result = await store.restore('ossdemo.txt', { type: 'ColdArchive', Days: 2 });
  2273. console.log(result.status);
  2274. ```
  2275. - Restore an history object
  2276. ```js
  2277. const versionId = 'object versionId';
  2278. const result = await store.restore('ossdemo.txt', { versionId });
  2279. console.log(result.status);
  2280. ```
  2281. ### .putSymlink(name, targetName[, options])
  2282. PutSymlink
  2283. parameters:
  2284. - name {String} object name
  2285. - targetName {String} target object name
  2286. - [options] {Object} optional parameters
  2287. - [storageClass] {String} the storage type include (Standard,IA,Archive)
  2288. - [meta] {Object} user meta, will send with `x-oss-meta-` prefix string
  2289. - [headers] {Object} extra headers, detail see [PutSymlink](https://help.aliyun.com/document_detail/45126.html#title-x71-l2b-7i8)
  2290. - res {Object} response info, including
  2291. - status {Number} response status
  2292. - headers {Object} response headers
  2293. - size {Number} response size
  2294. - rt {Number} request total use time (ms)
  2295. example:
  2296. ```js
  2297. const options = {
  2298. storageClass: 'IA',
  2299. meta: {
  2300. uid: '1',
  2301. slus: 'test.html'
  2302. }
  2303. };
  2304. const result = await store.putSymlink('ossdemo.txt', 'targetName', options);
  2305. console.log(result.res);
  2306. ```
  2307. putSymlink multiversion
  2308. ```js
  2309. const options = {
  2310. storageClass: 'IA',
  2311. meta: {
  2312. uid: '1',
  2313. slus: 'test.html'
  2314. }
  2315. };
  2316. const result = await store.putSymlink('ossdemo.txt', 'targetName', options);
  2317. console.log(result.res.headers['x-oss-version-id']);
  2318. ```
  2319. ### .getSymlink(name[, options])
  2320. GetSymlink
  2321. parameters:
  2322. - name {String} object name
  2323. - [options] {Object} optional parameters
  2324. - [versionId] {String} the version id of history object
  2325. Success will return
  2326. - targetName {String} target object name
  2327. - res {Object} response info, including
  2328. - status {Number} response status
  2329. - headers {Object} response headers
  2330. - size {Number} response size
  2331. - rt {Number} request total use time (ms)
  2332. example:
  2333. ```js
  2334. const result = await store.getSymlink('ossdemo.txt');
  2335. console.log(result.targetName);
  2336. ```
  2337. for history object
  2338. ```js
  2339. const versionId = 'object versionId';
  2340. const result = await store.getSymlink('ossdemo.txt', { versionId });
  2341. console.log(result.targetName);
  2342. ```
  2343. ### .initMultipartUpload(name[, options])
  2344. Before transmitting data in the Multipart Upload mode,
  2345. you must call the Initiate Multipart Upload interface to notify the OSS to initiate a Multipart Upload event.
  2346. The Initiate Multipart Upload interface returns a globally unique Upload ID created by the OSS server to identify this Multipart Upload event.
  2347. parameters:
  2348. - name {String} object name
  2349. - [options] {Object} optional parameters
  2350. - [timeout] {Number} the operation timeout
  2351. - [mime] Mime file type e.g.: application/octet-stream
  2352. - [meta] {Object} user meta, will send with `x-oss-meta-` prefix string
  2353. - [headers] {Object} extra headers
  2354. - 'Cache-Control' cache control for download, e.g.: `Cache-Control: public, no-cache`
  2355. - 'Content-Disposition' object name for download, e.g.: `Content-Disposition: somename`
  2356. - 'Content-Encoding' object content encoding for download, e.g.: `Content-Encoding: gzip`
  2357. - 'Expires' expires time for download, an absolute date and time. e.g.: `Tue, 08 Dec 2020 13:49:43 GMT`
  2358. - [x-oss-server-side-encryption]
  2359. Specify the server-side encryption algorithm used to upload each part of this object,Type: string, Valid value: AES256 `x-oss-server-side-encryption: AES256`<br>
  2360. if use in browser you should be set cors expose header x-oss-server-side-encryption
  2361. - See more: [InitiateMultipartUpload](https://help.aliyun.com/document_detail/31992.html?#title-wh0-a2h-rur)
  2362. Success will return:
  2363. - res {Object} response info, including
  2364. - status {Number} response status
  2365. - headers {Object} response headers
  2366. - [x-oss-server-side-encryption] if set request header x-oss-server-side-encryption, will return
  2367. - size {Number} response size
  2368. - rt {Number} request total use time (ms)
  2369. - bucket {String} bucket name
  2370. - name {String} object name store on OSS
  2371. - uploadId {String} upload id, use for uploadPart, completeMultipart
  2372. example:
  2373. ```js
  2374. const result = await store.initMultipartUpload('object');
  2375. console.log(result);
  2376. ```
  2377. ### .uploadPart(name, uploadId, partNo, file, start, end[, options])
  2378. After initiating a Multipart Upload event, you can upload data in parts based on the specified object name and Upload ID.
  2379. parameters:
  2380. - name {String} object name
  2381. - uploadId {String} get by initMultipartUpload api
  2382. - partNo {Number} range is 1-10000, If this range is exceeded, OSS returns the InvalidArgument's error code.
  2383. - file {File|String} is File or FileName, the whole file<br>
  2384. Multipart Upload requires that the size of any Part other than the last Part is greater than 100KB. <br>
  2385. In Node you can use File or FileName, but in browser you only can use File.
  2386. - start {Number} part start bytes e.g: 102400
  2387. - end {Number} part end bytes e.g: 204800
  2388. - [options] {Object} optional parameters
  2389. - [timeout] {Number} the operation timeout
  2390. Success will return:
  2391. - res {Object} response info, including
  2392. - status {Number} response status
  2393. - headers {Object} response headers
  2394. - size {Number} response size
  2395. - rt {Number} request total use time (ms)
  2396. - name {String} object name store on OSS
  2397. - etag {String} object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE"
  2398. example:
  2399. ```js
  2400. const name = 'object';
  2401. const result = await store.initMultipartUpload(name);
  2402. const uploadId = result.uploadId;
  2403. const file; //the data you want to upload, is a File or FileName(only in node)
  2404. //if file part is 10
  2405. const partSize = 100 * 1024;
  2406. const fileSize = 10 * partSize;//you need to calculate
  2407. const dones = [];
  2408. for (let i = 1; i <= 10; i++) {
  2409. const start = partSize * (i -1);
  2410. const end = Math.min(start + partSize, fileSize);
  2411. const part = await store.uploadPart(name, uploadId, i, file, start, end);
  2412. dones.push({
  2413. number: i,
  2414. etag: part.etag
  2415. });
  2416. console.log(part);
  2417. }
  2418. //end need to call completeMultipartUpload api
  2419. ```
  2420. ### .uploadPartCopy(name, uploadId, partNo, range, sourceData[, options])
  2421. Using Upload Part Copy, you can copy data from an existing object and upload a part of the data.
  2422. When copying a file larger than 1 GB, you must use the Upload Part Copy method. If you want to copy a file smaller than 1 GB, see Copy Object.
  2423. parameters:
  2424. - name {String} object name
  2425. - uploadId {String} get by initMultipartUpload api
  2426. - partNo {Number} range is 1-10000, If this range is exceeded, OSS returns the InvalidArgument's error code.
  2427. - range {String} Multipart Upload requires that the size of any Part other than the last Part is greater than 100KB, range value like `0-102400`
  2428. - sourceData {Object}
  2429. - sourceKey {String} the source object name
  2430. - sourceBucketName {String} the source bucket name
  2431. - [options] {Object} optional parameters
  2432. - [timeout] {Number} the operation timeout
  2433. - [versionId] {String} the version id of history object
  2434. - [headers] {Object} The following request header is used for the source objects specified by x-oss-copy-source.
  2435. - [x-oss-copy-source-if-match] default none<br>
  2436. If the ETAG value of the source object is equal to the ETAG value provided by the user, the system performs the Copy Object operation; otherwise, the system returns the 412 Precondition Failed message.
  2437. - [x-oss-copy-source-if-none-match] default none<br>
  2438. If the source object has not been modified since the time specified by the user, the system performs the Copy Object operation; otherwise, the system returns the 412 Precondition Failed message.
  2439. - [x-oss-copy-source-if-unmodified-since] default none<br>
  2440. If the time specified by the received parameter is the same as or later than the modification time of the file, the system transfers the file normally, and returns 200 OK; otherwise, the system returns 412 Precondition Failed.
  2441. - [x-oss-copy-source-if-modified-since] default none<br>
  2442. If the source object has been modified since the time specified by the user, the system performs the Copy Object operation; otherwise, the system returns the 412 Precondition Failed message.
  2443. Success will return:
  2444. - res {Object} response info, including
  2445. - status {Number} response status
  2446. - headers {Object} response headers
  2447. - size {Number} response size
  2448. - rt {Number} request total use time (ms)
  2449. - name {String} object name store on OSS
  2450. - etag {String} object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE"
  2451. example:
  2452. ```js
  2453. const name = 'object';
  2454. const result = await store.initMultipartUpload(name);
  2455. const partSize = 100 * 1024; //100kb
  2456. //if file part is 10
  2457. for (let i = 1; i <= 10; i++) {
  2458. const start = partSize * (i - 1);
  2459. const end = Math.min(start + partSize, fileSize);
  2460. const range = start + '-' + (end - 1);
  2461. const part = await store.uploadPartCopy(name, result.uploadId, i, range, {
  2462. sourceKey: 'sourceKey',
  2463. sourceBucketName: 'sourceBucketName'
  2464. });
  2465. console.log(part);
  2466. }
  2467. //end need complete api
  2468. ```
  2469. - use history object to uploadPartCopy
  2470. ```js
  2471. const versionId = 'object versionId';
  2472. const name = 'object';
  2473. const result = await store.initMultipartUpload(name);
  2474. const partSize = 100 * 1024; //100kb
  2475. //if file part is 10
  2476. for (let i = 1; i <= 10; i++) {
  2477. const start = partSize * (i - 1);
  2478. const end = Math.min(start + partSize, fileSize);
  2479. const range = start + '-' + (end - 1);
  2480. const part = await store.uploadPartCopy(
  2481. name,
  2482. result.uploadId,
  2483. i,
  2484. range,
  2485. {
  2486. sourceKey: 'sourceKey',
  2487. sourceBucketName: 'sourceBucketName'
  2488. },
  2489. {
  2490. versionId
  2491. }
  2492. );
  2493. console.log(part);
  2494. }
  2495. //end need complete api
  2496. ```
  2497. ### .completeMultipartUpload(name, uploadId, parts[, options])
  2498. After uploading all data parts, you must call the Complete Multipart Upload API to complete Multipart Upload for the entire file.
  2499. parameters:
  2500. - name {String} object name
  2501. - uploadId {String} get by initMultipartUpload api
  2502. - parts {Array} more part {Object} from uploadPartCopy, , each in the structure:
  2503. - number {Number} partNo
  2504. - etag {String} object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE"
  2505. - [options] {Object} optional parameters
  2506. - [timeout] {Number} the operation timeout
  2507. - [callback] {Object} The callback parameter is composed of a JSON string encoded in Base64,detail [see](https://www.alibabacloud.com/help/doc-detail/31989.htm)<br>
  2508. - url {String} After a file is uploaded successfully, the OSS sends a callback request to this URL.
  2509. - [host] {String} The host header value for initiating callback requests.
  2510. - body {String} The value of the request body when a callback is initiated, for example, key=${key}&etag=${etag}&my_var=${x:my_var}.
  2511. - [contentType] {String} The Content-Type of the callback requests initiatiated, It supports application/x-www-form-urlencoded and application/json, and the former is the default value.
  2512. - [callbackSNI] {Boolean} Specifies whether OSS sends Server Name Indication (SNI) to the origin address specified by callbackUrl when a callback request is initiated from the client.
  2513. - [customValue] {Object} Custom parameters are a map of key-values<br>
  2514. e.g.:
  2515. ```js
  2516. var customValue = { var1: 'value1', var2: 'value2' };
  2517. ```
  2518. - [headers] {Object} extra headers, detail see [CompleteMultipartUpload](https://help.aliyun.com/document_detail/31995.html?#title-nan-5y3-rjd)
  2519. Success will return:
  2520. - res {Object} response info, including
  2521. - status {Number} response status
  2522. - headers {Object} response headers
  2523. - size {Number} response size
  2524. - rt {Number} request total use time (ms)
  2525. - bucket {String} bucket name
  2526. - name {String} object name store on OSS
  2527. - etag {String} object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE"
  2528. - data {Object} callback server response data , sdk use JSON.parse() return
  2529. example:
  2530. ```js
  2531. //init multipart
  2532. const name = 'object';
  2533. const result = await store.initMultipartUpload(name);
  2534. //upload part
  2535. const file; //the data you want to upload, this example size is 10 * 100 * 1024
  2536. const fileSize;//you need to calculate
  2537. const partSize = 100 * 1024;//100kb
  2538. const done = [];
  2539. //if file part is 10
  2540. for (let i = 1; i <= 10; i++) {
  2541. const start = partSize * (i -1);
  2542. const end = Math.min(start + partSize, fileSize);
  2543. const data = file.slice(start, end);
  2544. const part = store.uploadPart(name, result.uploadId, i, data, 0, data.length);
  2545. console.log(part);
  2546. done.push({
  2547. number: i,
  2548. etag: part.res.headers.etag
  2549. });
  2550. }
  2551. //complete
  2552. const completeData = await store.completeMultipartUpload(name, result.uploadId, done);
  2553. console.log(completeData);
  2554. ```
  2555. ### .multipartUpload(name, file[, options])
  2556. Upload file with [OSS multipart][oss-multipart].<br>
  2557. this function contains initMultipartUpload, uploadPart, completeMultipartUpload.
  2558. When you use multipartUpload api,if you encounter problems with ConnectionTimeoutError, you should handle ConnectionTimeoutError in your business code. How to resolve ConnectionTimeoutError, you can decrease `partSize` size 、 Increase `timeout` 、Retry request ,
  2559. or give tips in your business code;
  2560. parameters:
  2561. - name {String} object name
  2562. - file {String|File(only support Browser)|Blob(only support Browser)|Buffer} file path or HTML5 Web File or web Blob or content buffer
  2563. - [options] {Object} optional args
  2564. - [parallel] {Number} the number of parts to be uploaded in parallel
  2565. - [partSize] {Number} the suggested size for each part, default `1024 * 1024`(1MB), minimum `100 * 1024`(100KB)
  2566. - [progress] {Function} function | async | Promise, the progress callback called after each
  2567. successful upload of one part, it will be given three parameters:
  2568. (percentage {Number}, checkpoint {Object}, res {Object})
  2569. - [checkpoint] {Object} the checkpoint to resume upload, if this is
  2570. provided, it will continue the upload from where interrupted,
  2571. otherwise a new multipart upload will be created.
  2572. - file {File} The file object selected by the user, if the browser is restarted, it needs the user to manually trigger the settings
  2573. - name {String} object key
  2574. - fileSize {Number} file size
  2575. - partSize {Number} part size
  2576. - uploadId {String} upload id
  2577. - doneParts {Array} An array of pieces that have been completed, including the object structure as follows
  2578. - number {Number} part number
  2579. - etag {String} part etag
  2580. - [meta] {Object} user meta, will send with `x-oss-meta-` prefix string
  2581. - [mime] {String} custom mime , will send with `Content-Type` entity header
  2582. - [callback] {Object} The callback parameter is composed of a JSON string encoded in Base64,detail [see](https://www.alibabacloud.com/help/doc-detail/31989.htm)<br>
  2583. - url {String} After a file is uploaded successfully, the OSS sends a callback request to this URL.
  2584. - [host] {String} The host header value for initiating callback requests.
  2585. - body {String} The value of the request body when a callback is initiated, for example, key=${key}&etag=${etag}&my_var=${x:my_var}.
  2586. - [contentType] {String} The Content-Type of the callback requests initiatiated, It supports application/x-www-form-urlencoded and application/json, and the former is the default value.
  2587. - [callbackSNI] {Boolean} Specifies whether OSS sends Server Name Indication (SNI) to the origin address specified by callbackUrl when a callback request is initiated from the client.
  2588. - [customValue] {Object} Custom parameters are a map of key-values<br>
  2589. e.g.:
  2590. ```js
  2591. var customValue = { var1: 'value1', var2: 'value2' };
  2592. ```
  2593. - [headers] {Object} extra headers, detail see [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616.html)
  2594. - 'Cache-Control' cache control for download, e.g.: `Cache-Control: public, no-cache`
  2595. - 'Content-Disposition' object name for download, e.g.: `Content-Disposition: somename`
  2596. - 'Content-Encoding' object content encoding for download, e.g.: `Content-Encoding: gzip`
  2597. - 'Expires' expires time for download, an absolute date and time. e.g.: `Tue, 08 Dec 2020 13:49:43 GMT`
  2598. - **NOTE**: Some headers are [disabled in browser][disabled-browser-headers]
  2599. - [timeout] {Number} Milliseconds before a request is considered to be timed out
  2600. - [disabledMD5] {Boolean} default true, it just work in Browser. if false,it means that MD5 is automatically calculated for uploaded files. **_NOTE:_** Synchronous computing tasks will block the main process
  2601. Success will return:
  2602. - res {Object} response info, including
  2603. - status {Number} response status
  2604. - headers {Object} response headers
  2605. - size {Number} response size
  2606. - rt {Number} request total use time (ms)
  2607. - bucket {String} bucket name
  2608. - name name {String} object name store on OSS
  2609. - etag {String} object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE"
  2610. - data {Object} callback server response data, sdk use JSON.parse() return
  2611. example:
  2612. - Upload using multipart
  2613. ```js
  2614. const result = await store.multipartUpload('object', '/tmp/file');
  2615. let savedCpt;
  2616. console.log(result);
  2617. const result = await store.multipartUpload('object', '/tmp/file', {
  2618. parallel: 4,
  2619. partSize: 1024 * 1024,
  2620. progress: function (p, cpt, res) {
  2621. console.log(p);
  2622. savedCpt = cpt;
  2623. console.log(cpt);
  2624. console.log(res.headers['x-oss-request-id']);
  2625. }
  2626. });
  2627. const result = await store.multipartUpload('object', '/tmp/file', {
  2628. checkpoint: savedCpt,
  2629. progress: function (p, cpt, res) {
  2630. //progress is generator
  2631. console.log(p);
  2632. console.log(cpt);
  2633. console.log(res.headers['x-oss-request-id']);
  2634. }
  2635. });
  2636. ```
  2637. - multipartUpload progress example
  2638. ```js
  2639. //async function
  2640. async function asyncProgress(p, cpt, res) {
  2641. console.log(p);
  2642. console.log(cpt);
  2643. console.log(res.headers['x-oss-request-id']);
  2644. }
  2645. const result1 = await store.multipartUpload('object', '/tmp/file', {
  2646. progress: asyncProgress
  2647. });
  2648. //function
  2649. function progress(p, cpt, res) {
  2650. console.log(p);
  2651. console.log(cpt);
  2652. console.log(res.headers['x-oss-request-id']);
  2653. }
  2654. const result2 = await store.multipartUpload('object', '/tmp/file', {
  2655. progress: progress
  2656. });
  2657. ```
  2658. - multipartUpload with abort
  2659. > tips: abort multipartUpload support on node and browser
  2660. ```js
  2661. //start upload
  2662. let abortCheckpoint;
  2663. store.multipartUpload('object', '/tmp/file', {
  2664. progress: function (p, cpt, res) {
  2665. abortCheckpoint = cpt;
  2666. }
  2667. }).then(res => {
  2668. // do something
  2669. }).catch(err => {
  2670. //if abort will catch abort event
  2671. if (err.name === 'abort') {
  2672. // handle abort
  2673. console.log('error: ', err.message)
  2674. }
  2675. });
  2676. // abort
  2677. store.abortMultipartUpload(abortCheckpoint.name, abortCheckpoint.uploadId);
  2678. ```
  2679. - multipartUpload with cancel
  2680. > tips: cancel multipartUpload support on node and browser
  2681. ```js
  2682. //start upload
  2683. try {
  2684. const result = await store.multipartUpload('object', '/tmp/file', {
  2685. checkpoint: savedCpt,
  2686. progress: function (p, cpt, res) {
  2687. console.log(p);
  2688. console.log(cpt);
  2689. console.log(res.headers['x-oss-request-id']);
  2690. }
  2691. });
  2692. } catch (err) {
  2693. //if cancel will catch cancel event
  2694. if (store.isCancel()) {
  2695. //do something
  2696. }
  2697. }
  2698. //the other event to cancel, for example: click event
  2699. //to cancel upload must use the same client instance
  2700. store.cancel();
  2701. ```
  2702. - multipartUpload with capture `ConnectionTimeoutError` error
  2703. ```js
  2704. //start upload
  2705. try {
  2706. const result = await store.multipartUpload('object', '/tmp/file', {
  2707. checkpoint: savedCpt,
  2708. progress: function (p, cpt, res) {
  2709. console.log(p);
  2710. console.log(cpt);
  2711. console.log(res.headers['x-oss-request-id']);
  2712. }
  2713. });
  2714. } catch (err) {
  2715. if (err.code === 'ConnectionTimeoutError') {
  2716. console.log('Woops,Woops ,timeout error!!!');
  2717. // do ConnectionTimeoutError operation
  2718. }
  2719. }
  2720. ```
  2721. ### .multipartUploadCopy(name, sourceData[, options])
  2722. Copy file with [OSS multipart][oss-multipart]. <br>
  2723. this function contains head, initMultipartUpload, uploadPartCopy, completeMultipartUpload.<br>
  2724. When copying a file larger than 1 GB, you should use the Upload Part Copy method. If you want to copy a file smaller than 1 GB, see Copy Object.
  2725. parameters:
  2726. - name {String} object name
  2727. - file {String|File} file path or HTML5 Web File
  2728. - [options] {Object} optional args
  2729. - [timeout] {Number} Milliseconds before a request is considered to be timed out
  2730. - [parallel] {Number} the number of parts to be uploaded in parallel
  2731. - [partSize] {Number} the suggested size for each part, defalut `1024 * 1024`(1MB), minimum `100 * 1024`(100KB)
  2732. - [versionId] {String} the version id of history object
  2733. - [progress] {Function} function | async | Promise, the progress callback called after each
  2734. successful upload of one part, it will be given three parameters:
  2735. (percentage {Number}, checkpoint {Object}, res {Object})
  2736. - [checkpoint] {Object} the checkpoint to resume upload, if this is
  2737. provided, it will continue the upload from where interrupted,
  2738. otherwise a new multipart upload will be created.
  2739. - [headers] {Object} extra headers, detail see [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616.html)
  2740. - 'Cache-Control' cache control for download, e.g.: `Cache-Control: public, no-cache`
  2741. - 'Content-Disposition' object name for download, e.g.: `Content-Disposition: somename`
  2742. - 'Content-Encoding' object content encoding for download, e.g.: `Content-Encoding: gzip`
  2743. - 'Expires' expires time for download, an absolute date and time. e.g.: `Tue, 08 Dec 2020 13:49:43 GMT`
  2744. - **NOTE**: Some headers are [disabled in browser][disabled-browser-headers]
  2745. - [copyheaders] {Object} only uploadPartCopy api used, detail [see](https://www.alibabacloud.com/help/doc-detail/31994.htm)
  2746. - [x-oss-copy-source-if-match] only uploadPartCopy api used, default none<br>
  2747. If the ETAG value of the source object is equal to the ETAG value provided by the user, the system performs the Copy Object operation; otherwise, the system returns the 412 Precondition Failed message.
  2748. - [x-oss-copy-source-if-none-match] only uploadPartCopy api used, default none<br>
  2749. If the source object has not been modified since the time specified by the user, the system performs the Copy Object operation; otherwise, the system returns the 412 Precondition Failed message.
  2750. - [x-oss-copy-source-if-unmodified-since] only uploadPartCopy api used, default none<br>
  2751. If the time specified by the received parameter is the same as or later than the modification time of the file, the system transfers the file normally, and returns 200 OK; otherwise, the system returns 412 Precondition Failed.
  2752. - [x-oss-copy-source-if-modified-since] only uploadPartCopy api used, default none<br>
  2753. If the source object has been modified since the time specified by the user, the system performs the Copy Object operation; otherwise, the system returns the 412 Precondition Failed message.
  2754. Success will return:
  2755. - res {Object} response info, including
  2756. - status {Number} response status
  2757. - headers {Object} response headers
  2758. - size {Number} response size
  2759. - rt {Number} request total use time (ms)
  2760. - bucket {String} bucket name
  2761. - name name {String} object name store on OSS
  2762. - etag {String} object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE"
  2763. example:
  2764. - Copy using multipart
  2765. ```js
  2766. const result = await store.multipartUploadCopy('object', {
  2767. sourceKey: 'sourceKey',
  2768. sourceBucketName: 'sourceBucketName'
  2769. });
  2770. let savedCpt;
  2771. console.log(result);
  2772. const result = await store.multipartUploadCopy(
  2773. 'object',
  2774. {
  2775. sourceKey: 'sourceKey',
  2776. sourceBucketName: 'sourceBucketName'
  2777. },
  2778. {
  2779. parallel: 4,
  2780. partSize: 1024 * 1024,
  2781. progress: function (p, cpt, res) {
  2782. console.log(p);
  2783. savedCpt = cpt;
  2784. console.log(cpt);
  2785. console.log(res.headers['x-oss-request-id']);
  2786. }
  2787. }
  2788. );
  2789. console.log(result);
  2790. const result = await store.multipartUploadCopy(
  2791. 'object',
  2792. {
  2793. sourceKey: 'sourceKey',
  2794. sourceBucketName: 'sourceBucketName'
  2795. },
  2796. {
  2797. checkpoint: savedCpt,
  2798. progress: function (p, cpt, res) {
  2799. console.log(p);
  2800. console.log(cpt);
  2801. console.log(res.headers['x-oss-request-id']);
  2802. }
  2803. }
  2804. );
  2805. console.log(result);
  2806. ```
  2807. - multipartUploadCopy with abort
  2808. ```js
  2809. // start upload
  2810. let abortCheckpoint;
  2811. store.multipartUploadCopy('object', {
  2812. sourceKey: 'sourceKey',
  2813. sourceBucketName: 'sourceBucketName'
  2814. }, {
  2815. progress: function (p, cpt, res) {
  2816. abortCheckpoint = cpt;
  2817. }
  2818. }).then(res => {
  2819. // do something
  2820. }).catch(err => {
  2821. //if abort will catch abort event
  2822. if (err.name === 'abort') {
  2823. // handle abort
  2824. console.log('error: ', err.message)
  2825. }
  2826. });
  2827. // the other event to abort, for example: click event
  2828. // to abort upload must use the same client instance
  2829. store.abortMultipartUpload(abortCheckpoint.name, abortCheckpoint.uploadId);
  2830. ```
  2831. - multipartUploadCopy with cancel
  2832. ```js
  2833. //start upload
  2834. try {
  2835. const result = await store.multipartUploadCopy(
  2836. 'object',
  2837. {
  2838. sourceKey: 'sourceKey',
  2839. sourceBucketName: 'sourceBucketName'
  2840. },
  2841. {
  2842. checkpoint: savedCpt,
  2843. progress: function (p, cpt, res) {
  2844. console.log(p);
  2845. console.log(cpt);
  2846. console.log(res.headers['x-oss-request-id']);
  2847. }
  2848. }
  2849. );
  2850. } catch (err) {
  2851. //if cancel will catch cancel event
  2852. if (store.isCancel()) {
  2853. //do something
  2854. }
  2855. }
  2856. //the other event to cancel, for example: click event
  2857. //to cancel upload must use the same client instance
  2858. store.cancel();
  2859. ```
  2860. - multipartUploadCopy with versionId
  2861. ```js
  2862. const versionId = 'object versionId';
  2863. //start upload
  2864. const result = await store.multipartUploadCopy(
  2865. 'object',
  2866. {
  2867. sourceKey: 'sourceKey',
  2868. sourceBucketName: 'sourceBucketName'
  2869. },
  2870. {
  2871. checkpoint: savedCpt,
  2872. progress: function (p, cpt, res) {
  2873. console.log(p);
  2874. console.log(cpt);
  2875. console.log(res.headers['x-oss-request-id']);
  2876. },
  2877. versionId
  2878. }
  2879. );
  2880. ```
  2881. ### .listParts(name, uploadId[, query, options])
  2882. The ListParts command can be used to list all successfully uploaded parts mapped to a specific upload ID, i.e.: those not completed and not
  2883. aborted.
  2884. parameters:
  2885. - name {String} object key
  2886. - uploadId {String} upload ID from initMultipartUpload api
  2887. - [query] {Object} query parameters
  2888. - [max-parts] {Number} The maximum part number in the response of the OSS. default value: 1000.
  2889. - [part-number-marker] {Number} Starting position of a specific list. A part is listed only when the part number is greater than the value of this parameter.
  2890. - [encoding-type] {String} Specify the encoding of the returned content and the encoding type. Optional value: url
  2891. - [options] {Object} optional args
  2892. - [timeout] {Number} the operation timeout
  2893. Success will return:
  2894. - res {Object} response info, including
  2895. - status {Number} response status
  2896. - headers {Object} response headers
  2897. - size {Number} response size
  2898. - rt {Number} request total use time (ms)
  2899. - uploadId {String} upload ID
  2900. - bucket {String} Specify the bucket name.
  2901. - name {String} object name
  2902. - PartNumberMarker {Number} Starting position of the part numbers in the listing result.
  2903. - nextPartNumberMarker {Number} If not all results are returned this time, the response request includes the NextPartNumberMarker element to indicate the value of PartNumberMarker in the next request.
  2904. - maxParts {Number} upload ID
  2905. - isTruncated {Boolean} Whether the returned result list for List Parts is truncated. The “true” indicates that not all results are returned; “false” indicates that all results are returned.
  2906. - parts {Array} The container that saves part information, each in the structure:
  2907. - PartNumber {Number} Part number.
  2908. - LastModified {Date} Time when a part is uploaded.
  2909. - ETag {String} ETag value in the content of the uploaded part.
  2910. - Size {Number} Size of the uploaded part.
  2911. example:
  2912. - List uploaded part
  2913. ```js
  2914. const result = await store.listParts('objcet', 'uploadId', {
  2915. 'max-parts': 1000
  2916. });
  2917. console.log(result);
  2918. ```
  2919. ### .listUploads(query[, options])
  2920. List on-going multipart uploads, i.e.: those not completed and not
  2921. aborted.
  2922. parameters:
  2923. - query {Object} query parameters
  2924. - [prefix] {String} the object key prefix
  2925. - [max-uploads] {Number} the max uploads to return
  2926. - [key-marker] {String} the object key marker, if `upload-id-marker`
  2927. is not provided, return uploads with `key > marker`, otherwise
  2928. return uploads with `key >= marker && uploadId > id-marker`
  2929. - [upload-id-marker] {String} the upload id marker, must be used
  2930. **WITH** `key-marker`
  2931. - [options] {Object} optional args
  2932. - [timeout] {Number} the operation timeout
  2933. example:
  2934. - List on-going multipart uploads
  2935. ```js
  2936. const result = await store.listUploads({
  2937. 'max-uploads': 100,
  2938. 'key-marker': 'my-object',
  2939. 'upload-id-marker': 'upload-id'
  2940. });
  2941. console.log(result);
  2942. ```
  2943. ### .abortMultipartUpload(name, uploadId[, options])
  2944. Abort a multipart upload for object.
  2945. parameters:
  2946. - name {String} the object name
  2947. - uploadId {String} the upload id
  2948. - [options] {Object} optional args
  2949. - [timeout] {Number} the operation timeout
  2950. example:
  2951. - Abort a multipart upload
  2952. ```js
  2953. const result = await store.abortMultipartUpload('object', 'upload-id');
  2954. console.log(result);
  2955. ```
  2956. ### .calculatePostSignature(policy)
  2957. get postObject params
  2958. parameters:
  2959. - policy {JSON or Object} policy must contain expiration and conditions.
  2960. Success will return postObject Api params.
  2961. Object:
  2962. - OSSAccessKeyId {String}
  2963. - Signature {String}
  2964. - policy {Object} response info
  2965. ### .getObjectTagging(name[, options])
  2966. Obtains the tags of an object.
  2967. parameters:
  2968. - name {String} the object name
  2969. - [options] {Object} optional args
  2970. - [versionId] {String} the version id of history object
  2971. Success will return the channel information.
  2972. object:
  2973. - tag {Object} the tag of object
  2974. - res {Object} response info
  2975. ### .putObjectTagging(name, tag[, options])
  2976. Configures or updates the tags of an object.
  2977. parameters:
  2978. - name {String} the object name
  2979. - tag {Object} tag, eg. `{var1: value1,var2:value2}`
  2980. - [options] {Object} optional args
  2981. - [versionId] {String} the version id of history object
  2982. Success will return the channel information.
  2983. object:
  2984. - status {Number} response status
  2985. - res {Object} response info
  2986. ### .deleteObjectTagging(name[, options])
  2987. Deletes the tag of a specified object.
  2988. parameters:
  2989. - name {String} the object name
  2990. - tag {Object} tag, eg. `{var1: value1,var2:value2}`
  2991. - [options] {Object} optional args
  2992. - [versionId] {String} the version id of history object
  2993. Success will return the channel information.
  2994. object:
  2995. - status {Number} response status
  2996. - res {Object} response info
  2997. ### .processObjectSave(sourceObject, targetObject, process[, targetBucket])
  2998. Persistency indicates that images are asynchronously stored in the specified Bucket
  2999. parameters:
  3000. - sourceObject {String} source object name
  3001. - targetObject {String} target object name
  3002. - process {String} process string
  3003. - [targetBucket] {String} target bucket
  3004. Success will return the channel information.
  3005. object:
  3006. - status {Number} response status
  3007. - res {Object} response info
  3008. ```js
  3009. const sourceObject = 'a.png';
  3010. const targetObject = 'b.png';
  3011. const process = 'image/watermark,text_aGVsbG8g5Zu+54mH5pyN5Yqh77yB,color_ff6a00';
  3012. await this.store.processObjectSave(sourceObject, targetObject, process);
  3013. ```
  3014. ## RTMP Operations
  3015. All operations function is [async], except `getRtmpUrl`.
  3016. async function format: `async functionName(...)`.
  3017. ### .putChannel(id, conf[, options])
  3018. Create a live channel.
  3019. parameters:
  3020. - id {String} the channel id
  3021. - conf {Object} the channel config
  3022. - [Description] {String} the channel description
  3023. - [Status] {String} the channel status: 'enabled' or 'disabled'
  3024. - [Target] {Object}
  3025. - [Type] {String} the data type for the channel, only 'HLS' is supported now
  3026. - [FragDuration] {Number} duration of a 'ts' segment
  3027. - [FragCount] {Number} the number of 'ts' segments in a 'm3u8'
  3028. - [PlaylistName] {String} the 'm3u8' name
  3029. - [options] {Object} optional parameters
  3030. - [timeout] {Number} the operation timeout
  3031. Success will return the channel information.
  3032. object:
  3033. - publishUrls {Array} the publish urls
  3034. - playUrls {Array} the play urls
  3035. - res {Object} response info
  3036. example:
  3037. - Create a live channel
  3038. ```js
  3039. const cid = 'my-channel';
  3040. const conf = {
  3041. Description: 'this is channel 1',
  3042. Status: 'enabled',
  3043. Target: {
  3044. Type: 'HLS',
  3045. FragDuration: '10',
  3046. FragCount: '5',
  3047. PlaylistName: 'playlist.m3u8'
  3048. }
  3049. };
  3050. const r = await this.store.putChannel(cid, conf);
  3051. console.log(r);
  3052. ```
  3053. ### .getChannel(id[, options])
  3054. Get live channel info.
  3055. parameters:
  3056. - id {String} the channel id
  3057. - [options] {Object} optional parameters
  3058. - [timeout] {Number} the operation timeout
  3059. Success will return the channel information.
  3060. object:
  3061. - data {Object} channel info, same as conf in [.putChannel](#putchannelid-conf-options)
  3062. - res {Object} response info
  3063. example:
  3064. - Get live channel info
  3065. ```js
  3066. const cid = 'my-channel';
  3067. const r = await this.store.getChannel(cid);
  3068. console.log(r);
  3069. ```
  3070. ### .deleteChannel(id[, options])
  3071. Delete a live channel.
  3072. parameters:
  3073. - id {String} the channel id
  3074. - [options] {Object} optional parameters
  3075. - [timeout] {Number} the operation timeout
  3076. Success will return the response infomation.
  3077. object:
  3078. - res {Object} response info
  3079. example:
  3080. - Delete a live channel
  3081. ```js
  3082. const cid = 'my-channel';
  3083. const r = await this.store.deleteChannel(cid);
  3084. console.log(r);
  3085. ```
  3086. ### .putChannelStatus(id, status[, options])
  3087. Change the live channel status.
  3088. parameters:
  3089. - id {String} the channel id
  3090. - status {String} the status: 'enabled' or 'disabled'
  3091. - [options] {Object} optional parameters
  3092. - [timeout] {Number} the operation timeout
  3093. Success will return the response information.
  3094. object:
  3095. - res {Object} response info
  3096. example:
  3097. - Disable a live channel
  3098. ```js
  3099. const cid = 'my-channel';
  3100. const r = await this.store.putChannelStatus(cid, 'disabled');
  3101. console.log(r);
  3102. ```
  3103. ### .getChannelStatus(id[, options])
  3104. Get the live channel status.
  3105. parameters:
  3106. - id {String} the channel id
  3107. - [options] {Object} optional parameters
  3108. - [timeout] {Number} the operation timeout
  3109. Success will return the channel status information.
  3110. object:
  3111. - data {Object}
  3112. - Status {String} the channel status: 'Live' or 'Idle'
  3113. - [ConnectedTime] {String} the connected time of rtmp pushing
  3114. - [RemoteAddr] {String} the remote addr of rtmp pushing
  3115. - [Video] {Object} the video parameters (Width/Height/FrameRate/Bandwidth/Codec)
  3116. - [Audio] {Object} the audio parameters (Bandwidth/SampleRate/Codec)
  3117. - res {Object} response info
  3118. example:
  3119. - Get a live channel status
  3120. ```js
  3121. const cid = 'my-channel';
  3122. const r = await this.store.getChannelStatus(cid);
  3123. console.log(r);
  3124. // { Status: 'Live',
  3125. // ConnectedTime: '2016-04-12T11:51:03.000Z',
  3126. // RemoteAddr: '42.120.74.98:53931',
  3127. // Video:
  3128. // { Width: '672',
  3129. // Height: '378',
  3130. // FrameRate: '29',
  3131. // Bandwidth: '60951',
  3132. // Codec: 'H264' },
  3133. // Audio: { Bandwidth: '5959', SampleRate: '22050', Codec: 'AAC' }
  3134. // }
  3135. ```
  3136. ### .listChannels(query[, options])
  3137. List channels.
  3138. parameters:
  3139. - query {Object} parameters for list
  3140. - prefix {String}: the channel id prefix (returns channels with this prefix)
  3141. - marker {String}: the channle id marker (returns channels after this id)
  3142. - max-keys {Number}: max number of channels to return
  3143. - [options] {Object} optional parameters
  3144. - [timeout] {Number} the operation timeout
  3145. Success will return the channel list.
  3146. object:
  3147. - channels {Array} the channels, each in the structure:
  3148. - Name {String} the channel id
  3149. - Description {String} the channel description
  3150. - Status {String} the channel status
  3151. - LastModified {String} the last modification time of the channel
  3152. - PublishUrls {Array} the publish urls for the channel
  3153. - PlayUrls {Array} the play urls for the channel
  3154. - nextMarker: result.data.NextMarker || null,
  3155. - isTruncated: result.data.IsTruncated === 'true'
  3156. - res {Object} response info
  3157. example:
  3158. - List live channels
  3159. ```js
  3160. const r = await this.store.listChannels({
  3161. prefix: 'my-channel',
  3162. 'max-keys': 3
  3163. });
  3164. console.log(r);
  3165. ```
  3166. ### .getChannelHistory(id[, options])
  3167. Get the live channel history.
  3168. parameters:
  3169. - id {String} the channel id
  3170. - [options] {Object} optional parameters
  3171. - [timeout] {Number} the operation timeout
  3172. Success will return the history information.
  3173. object:
  3174. - records {Object} the pushing records, each in the structure:
  3175. - StartTime {String} the start time
  3176. - EndTime {String} the end time
  3177. - RemoteAddr {String} the remote addr
  3178. - res {Object} response info
  3179. example:
  3180. - Get the live channel history
  3181. ```js
  3182. const cid = 'my-channel';
  3183. const r = await this.store.getChannelHistory(cid);
  3184. console.log(r);
  3185. ```
  3186. ### .createVod(id, name, time[, options])
  3187. Create a VOD playlist for the channel.
  3188. parameters:
  3189. - id {String} the channel id
  3190. - name {String} the playlist name
  3191. - time {Object} the duration time
  3192. - startTime {Number} the start time in epoch seconds
  3193. - endTime {Number} the end time in epoch seconds
  3194. - [options] {Object} optional parameters
  3195. - [timeout] {Number} the operation timeout
  3196. Success will return the response information.
  3197. object:
  3198. - res {Object} response info
  3199. example:
  3200. - Create a vod playlist of a live channel
  3201. ```js
  3202. const cid = 'my-channel';
  3203. const r = await this.store.createVod(cid, 're-play', {
  3204. startTime: 1460464870,
  3205. endTime: 1460465877
  3206. });
  3207. console.log(r);
  3208. ```
  3209. ### .getRtmpUrl(channelId[, options])
  3210. Get signatured rtmp url for publishing.
  3211. parameters:
  3212. - channelId {String} the channel id
  3213. - [options] {Object} optional parameters
  3214. - [expires] {Number} the expire time in seconds of the url
  3215. - [params] {Object} the additional paramters for url, e.g.: {playlistName: 'play.m3u8'}
  3216. - [timeout] {Number} the operation timeout
  3217. Success will return the rtmp url.
  3218. example:
  3219. - Get a rtmp url.
  3220. ```js
  3221. const cid = 'my-channel';
  3222. const url = this.store.getRtmpUrl(this.cid, {
  3223. params: {
  3224. playlistName: 'play.m3u8'
  3225. },
  3226. expires: 3600
  3227. });
  3228. console.log(url);
  3229. // rtmp://ossliveshow.oss-cn-hangzhou.aliyuncs.com/live/tl-channel?OSSAccessKeyId=T0cqQWBk2ThfRS6m&Expires=1460466188&Signature=%2BnzTtpyxUWDuQn924jdS6b51vT8%3D
  3230. ```
  3231. ## Create A Image Service Instance
  3232. Each Image Service instance required `accessKeyId`, `accessKeySecret`, `bucket` and `imageHost`.
  3233. ### oss.ImageClient(options)
  3234. Create a Image service instance.
  3235. options:
  3236. - imageHost {String} your image service domain that binding to a OSS bucket
  3237. - accessKeyId {String} access key you create on aliyun console website
  3238. - accessKeySecret {String} access secret you create
  3239. - bucket {String} the default bucket you want to access
  3240. If you don't have any bucket, please use `putBucket()` create one first.
  3241. - [region] {String} the bucket data region location, please see [Data Regions](#data-regions),
  3242. default is `oss-cn-hangzhou`
  3243. Current available: `oss-cn-hangzhou`, `oss-cn-qingdao`, `oss-cn-beijing`, `oss-cn-hongkong` and `oss-cn-shenzhen`
  3244. - [internal] {Boolean} access OSS with aliyun internal network or not, default is `false`
  3245. If your servers are running on aliyun too, you can set `true` to save lot of money.
  3246. - [timeout] {String|Number} instance level timeout for all operations, default is `60s`
  3247. example:
  3248. ```js
  3249. const oss = require('ali-oss');
  3250. const imgClient = oss.ImageClient({
  3251. accessKeyId: 'your access key',
  3252. accessKeySecret: 'your access secret',
  3253. bucket: 'my_image_bucket',
  3254. imageHost: 'thumbnail.myimageservice.com'
  3255. });
  3256. ```
  3257. ## Image Operations
  3258. All operations function is [async], except `imgClient.signatureUrl`.
  3259. async function format: `async functionName(...)`.
  3260. ### imgClient.get(name, file[, options])
  3261. Get an image from the image channel.
  3262. parameters:
  3263. - name {String} image object name with operation style store on OSS
  3264. - [file] {String|WriteStream} file path or WriteStream instance to store the image
  3265. If `file` is null or ignore this parameter, function will return info contains `content` property.
  3266. - [options] {Object} optional parameters
  3267. - [timeout] {Number} the operation timeout
  3268. - [headers] {Object} extra headers, detail see [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616.html)
  3269. - 'If-Modified-Since' object modified after this time will return 200 and object meta,
  3270. otherwise return 304 not modified
  3271. - 'If-Unmodified-Since' object modified before this time will return 200 and object meta,
  3272. otherwise throw PreconditionFailedError
  3273. - 'If-Match' object etag equal this will return 200 and object meta,
  3274. otherwise throw PreconditionFailedError
  3275. - 'If-None-Match' object etag not equal this will return 200 and object meta,
  3276. otherwise return 304 not modified
  3277. Success will return the info contains response.
  3278. object:
  3279. - [content] {Buffer} file content buffer if `file` parameter is null or ignore
  3280. - res {Object} response info, including
  3281. - status {Number} response status
  3282. - headers {Object} response headers
  3283. - size {Number} response size
  3284. - rt {Number} request total use time (ms)
  3285. If object not exists, will throw NoSuchKeyError.
  3286. example:
  3287. - Get an exists image with a style and store it to the local file
  3288. ```js
  3289. const imagepath = '/home/ossdemo/demo.jpg';
  3290. await imgClient.get('ossdemo/demo.jpg@200w_200h', filepath);
  3291. ```
  3292. \_ Store image to a writestream
  3293. ```js
  3294. await imgClient.get('ossdemo/demo.jpg@200w_200h', somestream);
  3295. ```
  3296. - Get an image content buffer
  3297. ```js
  3298. const result = await imgClient.get('ossdemo/demo.jpg@200w_200h');
  3299. console.log(Buffer.isBuffer(result.content));
  3300. ```
  3301. - Get a not exists object or a not image object
  3302. ```js
  3303. const imagepath = '/home/ossdemo/demo.jpg';
  3304. await imgClient.get('ossdemo/not-exists-demo.jpg@200w_200h', filepath);
  3305. // will throw NoSuchKeyError
  3306. ```
  3307. ### imgClient.getStream(name[, options])
  3308. Get an image read stream.
  3309. parameters:
  3310. - name {String} image object name with operation style store on OSS
  3311. - [options] {Object} optional parameters
  3312. - [timeout] {Number} the operation timeout
  3313. - [headers] {Object} extra headers
  3314. - 'If-Modified-Since' object modified after this time will return 200 and object meta,
  3315. otherwise return 304 not modified
  3316. - 'If-Unmodified-Since' object modified before this time will return 200 and object meta,
  3317. otherwise throw PreconditionFailedError
  3318. - 'If-Match' object etag equal this will return 200 and object meta,
  3319. otherwise throw PreconditionFailedError
  3320. - 'If-None-Match' object etag not equal this will return 200 and object meta,
  3321. otherwise return 304 not modified
  3322. Success will return the stream instance and response info.
  3323. object:
  3324. - stream {ReadStream} readable stream instance. If response status is not `200`, stream will be `null`.
  3325. - res {Object} response info, including
  3326. - status {Number} response status
  3327. - headers {Object} response headers
  3328. - size {Number} response size
  3329. - rt {Number} request total use time (ms)
  3330. If object not exists, will throw NoSuchKeyError.
  3331. example:
  3332. - Get an exists image object stream
  3333. ```js
  3334. const result = await imgClient.getStream('ossdemo/demo.jpg@200w_200h');
  3335. result.stream.pipe(fs.createWriteStream('some demo.jpg'));
  3336. ```
  3337. ### imgClient.getExif(name[, options])
  3338. Get a image exif info by image object name from the image channel.
  3339. parameters:
  3340. - name {String} image object name
  3341. - [options] {Object} optional parameters
  3342. - [timeout] {Number} the operation timeout
  3343. Success will return the info contains response.
  3344. object:
  3345. - res {Object} response info, including
  3346. - status {Number} response status
  3347. - headers {Object} response headers
  3348. - size {Number} response size
  3349. - rt {Number} request total use time (ms)
  3350. - data {Object} image exif object
  3351. If object don't have exif, will throw 400 BadRequest.
  3352. example:
  3353. ```js
  3354. const result = await imgClient.getExif('demo.jpg');
  3355. // resut:
  3356. // {
  3357. // res: {
  3358. // status: 200,
  3359. // statusCode: 200,
  3360. // headers: {
  3361. // server: "Tengine",
  3362. // content - type: "application/json",
  3363. // content - length: "148",
  3364. // connection: "keep-alive",
  3365. // date: "Tue, 31 Mar 2015 11:06:32 GMT",
  3366. // "last-modified": "Mon, 30 Mar 2015 10:46:35 GMT"
  3367. // },
  3368. // size: 148,
  3369. // aborted: false,
  3370. // rt: 461,
  3371. // keepAliveSocket: false
  3372. // },
  3373. // data: {
  3374. // FileSize: 343683,
  3375. // ImageHeight: 1200,
  3376. // ImageWidth: 1600,
  3377. // Orientation: 1
  3378. // }
  3379. // }
  3380. ```
  3381. ### imgClient.getInfo(name[, options])
  3382. Get a image info and exif info by image object name from the image channel.
  3383. parameters:
  3384. - name {String} image object name
  3385. - [options] {Object} optional parameters
  3386. - [timeout] {Number} the operation timeout
  3387. Success will return the info contains response.
  3388. object:
  3389. - res {Object} response info, including
  3390. - status {Number} response status
  3391. - headers {Object} response headers
  3392. - size {Number} response size
  3393. - rt {Number} request total use time (ms)
  3394. - data {Object} image exif object
  3395. example:
  3396. ```js
  3397. const result = await imgClient.getInfo('demo.jpg');
  3398. // resut:
  3399. // {
  3400. // res: {
  3401. // status: 200,
  3402. // statusCode: 200,
  3403. // headers: {
  3404. // server: "Tengine",
  3405. // content - type: "application/json",
  3406. // content - length: "148",
  3407. // connection: "keep-alive",
  3408. // date: "Tue, 31 Mar 2015 11:06:32 GMT",
  3409. // "last-modified": "Mon, 30 Mar 2015 10:46:35 GMT"
  3410. // },
  3411. // size: 148,
  3412. // aborted: false,
  3413. // rt: 461,
  3414. // keepAliveSocket: false
  3415. // },
  3416. // data: {
  3417. // FileSize: 343683,
  3418. // Format: "jpg",
  3419. // ImageHeight: 1200,
  3420. // ImageWidth: 1600,
  3421. // Orientation: 1
  3422. // }
  3423. // }
  3424. ```
  3425. ### imgClient.putStyle(name, style[, options])
  3426. // TODO
  3427. ### imgClient.getStyle(name[, options])
  3428. Get a style by name from the image channel.
  3429. parameters:
  3430. - name {String} image style name
  3431. - [options] {Object} optional parameters
  3432. - [timeout] {Number} the operation timeout
  3433. Success will return the info contains response.
  3434. object:
  3435. - res {Object} response info, including
  3436. - status {Number} response status
  3437. - headers {Object} response headers
  3438. - size {Number} response size
  3439. - rt {Number} request total use time (ms)
  3440. - data {Object} styles object
  3441. - Name {String} style name
  3442. - Content {String} style content
  3443. - CreateTime {String} style create time
  3444. - LastModifyTime {String} style last modify time
  3445. example:
  3446. ```js
  3447. const result = await imgClient.getStyle('400');
  3448. // resut:
  3449. // {
  3450. // res: {
  3451. // status: 200,
  3452. // statusCode: 200,
  3453. // headers: {
  3454. // server: "Tengine",
  3455. // content - type: "application/xml",
  3456. // content - length: "234",
  3457. // connection: "keep-alive",
  3458. // date: "Tue, 31 Mar 2015 10:58:20 GMT"
  3459. // },
  3460. // size: 234,
  3461. // aborted: false,
  3462. // rt: 398,
  3463. // keepAliveSocket: false
  3464. // },
  3465. // data: {
  3466. // Name: "400",
  3467. // Content: "400w_90Q_1x.jpg",
  3468. // CreateTime: "Thu, 19 Mar 2015 08:34:21 GMT",
  3469. // LastModifyTime: "Thu, 19 Mar 2015 08:34:21 GMT"
  3470. // }
  3471. // }
  3472. ```
  3473. ### imgClient.listStyle([options])
  3474. Get all styles from the image channel.
  3475. parameters:
  3476. - [options] {Object} optional parameters
  3477. - [timeout] {Number} the operation timeout
  3478. Success will return the info contains response.
  3479. object:
  3480. - res {Object} response info, including
  3481. - status {Number} response status
  3482. - headers {Object} response headers
  3483. - size {Number} response size
  3484. - rt {Number} request total use time (ms)
  3485. - data {Array} styles array, a style object:
  3486. - Name {String} style name
  3487. - Content {String} style content
  3488. - CreateTime {String} style create time
  3489. - LastModifyTime {String} style last modify time
  3490. example:
  3491. ```js
  3492. const result = await imgClient.listStyle();
  3493. // resut:
  3494. // {
  3495. // res: {
  3496. // status: 200,
  3497. // statusCode: 200,
  3498. // headers: {
  3499. // server: "Tengine",
  3500. // content - type: "application/xml",
  3501. // content - length: "913",
  3502. // connection: "keep-alive",
  3503. // date: "Tue, 31 Mar 2015 10:47:32 GMT"
  3504. // },
  3505. // size: 913,
  3506. // aborted: false,
  3507. // rt: 1911,
  3508. // keepAliveSocket: false
  3509. // },
  3510. // data: [{
  3511. // Name: "200-200",
  3512. // Content: "0e_200w_200h_0c_0i_0o_90Q_1x.jpg",
  3513. // CreateTime: "Thu, 19 Mar 2015 08:28:08 GMT",
  3514. // LastModifyTime: "Thu, 19 Mar 2015 08:28:08 GMT"
  3515. // }, {
  3516. // Name: "800",
  3517. // Content: "800w_90Q_1x.jpg",
  3518. // CreateTime: "Thu, 19 Mar 2015 08:29:15 GMT",
  3519. // LastModifyTime: "Thu, 19 Mar 2015 08:29:15 GMT"
  3520. // }, {
  3521. // Name: "400",
  3522. // Content: "400w_90Q_1x.jpg",
  3523. // CreateTime: "Thu, 19 Mar 2015 08:34:21 GMT",
  3524. // LastModifyTime: "Thu, 19 Mar 2015 08:34:21 GMT"
  3525. // }, {
  3526. // Name: "600",
  3527. // Content: "600w_90Q_1x.jpg",
  3528. // CreateTime: "Thu, 19 Mar 2015 08:35:02 GMT",
  3529. // LastModifyTime: "Thu, 19 Mar 2015 08:35:02 GMT"
  3530. // }]
  3531. // }
  3532. ```
  3533. ### imgClient.deleteStyle(name[, options])
  3534. // TODO
  3535. ### imgClient.signatureUrl(name)
  3536. Create a signature url for directly download.
  3537. parameters:
  3538. - name {String} image object name with operation style store on OSS
  3539. - [options] {Object} optional parameters
  3540. - [expires] {Number} after expires seconds, the url will become invalid, default is `1800`
  3541. - [timeout] {Number} the operation timeout
  3542. Success will return full signature url.
  3543. example:
  3544. ```js
  3545. const url = imgClient.signatureUrl('name');
  3546. ```
  3547. ## Cluster Mode
  3548. Cluster mode now only support object operations.
  3549. ```js
  3550. const Cluster = require('ali-oss').ClusterClient;
  3551. const client = Cluster({
  3552. cluster: [
  3553. {
  3554. host: 'host1',
  3555. accessKeyId: 'id1',
  3556. accessKeySecret: 'secret1'
  3557. },
  3558. {
  3559. host: 'host2',
  3560. accessKeyId: 'id2',
  3561. accessKeySecret: 'secret2'
  3562. }
  3563. ],
  3564. schedule: 'masterSlave' //default is `roundRobin`
  3565. });
  3566. // listen error event to logging error
  3567. client.on('error', function (err) {
  3568. console.error(err.stack);
  3569. });
  3570. // client init ready
  3571. client.ready(function () {
  3572. console.log('cluster client init ready, go ahead!');
  3573. });
  3574. ```
  3575. ### Get Methods
  3576. Will choose an alive client by schedule(`masterSlave` or `roundRobin`).
  3577. - `client.get()`
  3578. - `client.head()`
  3579. - `client.getStream()`
  3580. - `client.list()`
  3581. - `client.signatureUrl()`
  3582. - `client.chooseAvailable()` - choose an available client by schedule.
  3583. - `client.getACL()`
  3584. ### Put Methods
  3585. Will put to all clients.
  3586. - `client.put()`
  3587. - `client.putStream()`
  3588. - `client.delete()`
  3589. - `client.deleteMulti()`
  3590. - `client.copy()`
  3591. - `client.putMeta()`
  3592. - `client.putACL()`
  3593. - `client.restore()`
  3594. ## Known Errors
  3595. Each error return by OSS server will contains these properties:
  3596. - name {String} error name
  3597. - message {String} error message
  3598. - requestId {String} uuid for this request, if you meet some unhandled problem,
  3599. you can send this request id to OSS engineer to find out what's happend.
  3600. - hostId {String} OSS cluster name for this request
  3601. ### ResponseTimeoutError
  3602. The default timeout is 60 seconds. Please set the timeout as needed. The timeout unit is milliseconds.
  3603. ```javascript
  3604. client.get('example.txt', { timeout: 60000 * 2 });
  3605. client.get('example.txt', { headers: { Range: `bytes=0-${1024 * 1024 * 100}` } }); // Download the first 100MB
  3606. ```
  3607. ### ConnectionTimeoutError
  3608. The network link timed out. Please check the network status. If there is no problem with the network, please reduce the partSize or increase the timeout.
  3609. ```javascript
  3610. const client = new OSS({ ak, sk, retryMax: 10 });
  3611. client.multipartUpload('example.txt', { timeout: 60000 * 2 });
  3612. client.multipartUpload('example.txt', { partSize: 1024 * 512 }); // partSize 512KB
  3613. ```
  3614. ### The following table lists the OSS error codes:
  3615. [More code info](https://help.aliyun.com/knowledge_detail/32005.html)
  3616. | name | code | status | message | message in Chinese |
  3617. | ---------------------------------------- | ----------------------------------- | ------ | ------------------------------------------------ | -------------------------------------- |
  3618. | AccessDeniedError | AccessDenied | 403 | Access Denied | 拒绝访问 |
  3619. | BucketAlreadyExistsError | BucketAlreadyExists | 409 | Bucket already exists | Bucket 已经存在 |
  3620. | BucketNotEmptyError | BucketNotEmpty | 409 | Bucket is not empty | Bucket 不为空 |
  3621. | RestoreAlreadyInProgressError | RestoreAlreadyInProgress | 409 | The restore operation is in progress. | restore 操作正在进行中 |
  3622. | OperationNotSupportedError | OperationNotSupported | 400 | The operation is not supported for this resource | 该资源暂不支持restore操作 |
  3623. | EntityTooLargeError | EntityTooLarge | 400 | Entity too large | 实体过大 |
  3624. | EntityTooSmallError | EntityTooSmall | 400 | Entity too small | 实体过小 |
  3625. | FileGroupTooLargeError | FileGroupTooLarge | 400 | File group too large | 文件组过大 |
  3626. | InvalidLinkNameError | InvalidLinkName | 400 | Link name can't be the same as the object name | Object Link 与指向的 Object 同名 |
  3627. | LinkPartNotExistError | LinkPartNotExist | 400 | Can't link to not exists object | Object Link 中指向的 Object 不存在 |
  3628. | ObjectLinkTooLargeError | ObjectLinkTooLarge | 400 | Too many links to this object | Object Link 中 Object 个数过多 |
  3629. | FieldItemTooLongError | FieldItemTooLong | 400 | Post form fields items too large | Post 请求中表单域过大 |
  3630. | FilePartInterityError | FilePartInterity | 400 | File part has changed | 文件 Part 已改变 |
  3631. | FilePartNotExistError | FilePartNotExist | 400 | File part not exists | 文件 Part 不存在 |
  3632. | FilePartStaleError | FilePartStale | 400 | File part stale | 文件 Part 过时 |
  3633. | IncorrectNumberOfFilesInPOSTRequestError | IncorrectNumberOfFilesInPOSTRequest | 400 | Post request contains invalid number of files | Post 请求中文件个数非法 |
  3634. | InvalidArgumentError | InvalidArgument | 400 | Invalid format argument | 参数格式错误 |
  3635. | InvalidAccessKeyIdError | InvalidAccessKeyId | 400 | Access key id not exists | Access Key ID 不存在 |
  3636. | InvalidBucketNameError | InvalidBucketName | 400 | Invalid bucket name | 无效的 Bucket 名字 |
  3637. | InvalidDigestError | InvalidDigest | 400 | Invalid digest | 无效的摘要 |
  3638. | InvalidEncryptionAlgorithmError | InvalidEncryptionAlgorithm | 400 | Invalid encryption algorithm | 指定的熵编码加密算法错误 |
  3639. | InvalidObjectNameError | InvalidObjectName | 400 | Invalid object name | 无效的 Object 名字 |
  3640. | InvalidPartError | InvalidPart | 400 | Invalid part | 无效的 Part |
  3641. | InvalidPartOrderError | InvalidPartOrder | 400 | Invalid part order | 无效的 part 顺序 |
  3642. | InvalidPolicyDocumentError | InvalidPolicyDocument | 400 | Invalid policy document | 无效的 Policy 文档 |
  3643. | InvalidTargetBucketForLoggingError | InvalidTargetBucketForLogging | 400 | Invalid bucket on logging operation | Logging 操作中有无效的目标 bucket |
  3644. | InternalError | Internal | 500 | OSS server internal error | OSS 内部发生错误 |
  3645. | MalformedXMLError | MalformedXML | 400 | Malformed XML format | XML 格式非法 |
  3646. | MalformedPOSTRequestError | MalformedPOSTRequest | 400 | Invalid post body format | Post 请求的 body 格式非法 |
  3647. | MaxPOSTPreDataLengthExceededError | MaxPOSTPreDataLengthExceeded | 400 | Post extra data too large | Post 请求上传文件内容之外的 body 过大 |
  3648. | MethodNotAllowedError | MethodNotAllowed | 405 | Not allowed method | 不支持的方法 |
  3649. | MissingArgumentError | MissingArgument | 411 | Missing argument | 缺少参数 |
  3650. | MissingContentLengthError | MissingContentLength | 411 | Missing `Content-Length` header | 缺少内容长度 |
  3651. | NoSuchBucketError | NoSuchBucket | 404 | Bucket not exists | Bucket 不存在 |
  3652. | NoSuchKeyError | NoSuchKey | 404 | Object not exists | 文件不存在 |
  3653. | NoSuchUploadError | NoSuchUpload | 404 | Multipart upload id not exists | Multipart Upload ID 不存在 |
  3654. | NotImplementedError | NotImplemented | 501 | Not implemented | 无法处理的方法 |
  3655. | PreconditionFailedError | PreconditionFailed | 412 | Pre condition failed | 预处理错误 |
  3656. | RequestTimeTooSkewedError | RequestTimeTooSkewed | 403 | Request time exceeds 15 minutes to server time | 发起请求的时间和服务器时间超出 15 分钟 |
  3657. | RequestTimeoutError | RequestTimeout | 400 | Request timeout | 请求超时 |
  3658. | RequestIsNotMultiPartContentError | RequestIsNotMultiPartContent | 400 | Invalid post content-type | Post 请求 content-type 非法 |
  3659. | SignatureDoesNotMatchError | SignatureDoesNotMatch | 403 | Invalid signature | 签名错误 |
  3660. | TooManyBucketsError | TooManyBuckets | 400 | Too many buckets on this user | 用户的 Bucket 数目超过限制 |
  3661. | RequestError | RequestError | -1 | network error | 网络出现中断或异常 |
  3662. | ConnectionTimeoutError | ConnectionTimeoutError | -2 | request connect timeout | 请求连接超时 |
  3663. | SecurityTokenExpiredError | SecurityTokenExpired | 403 | sts Security Token Expired | sts Security Token 超时失效 |
  3664. [generator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*
  3665. [oss-sts]: https://help.aliyun.com/document_detail/oss/practice/ram_guide.html
  3666. [browser-sample]: https://github.com/rockuw/oss-in-browser
  3667. [oss-multipart]: https://help.aliyun.com/document_detail/31992.html
  3668. [disabled-browser-headers]: https://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method