UNPKG

ali-oss

Version:

aliyun oss(object storage service) node client

1,727 lines (1,296 loc) 135 kB
oss-js-sdk ======= [![NPM version][npm-image]][npm-url] [![build status][travis-image]][travis-url] [![coverage][cov-image]][cov-url] [![David deps][david-image]][david-url] [npm-image]: https://img.shields.io/npm/v/ali-oss.svg?style=flat-square [npm-url]: https://npmjs.org/package/ali-oss [travis-image]: https://img.shields.io/travis/ali-sdk/ali-oss/master.svg?style=flat-square [travis-url]: https://travis-ci.org/ali-sdk/ali-oss.svg?branch=master [cov-image]: http://codecov.io/github/ali-sdk/ali-oss/coverage.svg?branch=master [cov-url]: http://codecov.io/github/ali-sdk/ali-oss?branch=master [david-image]: https://img.shields.io/david/ali-sdk/ali-oss.svg?style=flat-square [david-url]: https://david-dm.org/ali-sdk/ali-oss aliyun OSS(Object Storage Service) js client for Node and Browser env. `NOTE`: For SDK `5.X` document, please go to [README.md](https://github.com/ali-sdk/ali-oss/blob/5.x/README.md) ## Install ```bash npm install ali-oss --save ``` ## Compatibility ### Node Node.js >= 8.0.0 required. You can use 4.x in Node.js < 8. ### Browser - IE >= 10 & Edge - Major versions of Chrome/Firefox/Safari - Major versions of Android/iOS/WP `Note`: - 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) ### QA You can join DingDing Talk Group, [Group Link](https://qr.dingtalk.com/action/joingroup?code=v1,k1,inkSDqCxm7LilkaR/kknRVBDQ8PDA0Lj5hj4Cf9io3w=&_dt_no_comment=1&origin=11) <img src="task/dingding.jpg" height="400" title="dingding" width="300"> ## License [MIT](LICENSE) # OSS Usage OSS, Object Storage Service. Equal to well known Amazon [S3](http://aws.amazon.com/s3/). All operation use es7 async/await to implement. All api is async function. ## Summary - [Node Usage](#node-usage) - [Browser Usage](#browser-usage) - [Data Regions](#data-regions) - [Create Account](#create-account) - [Create A Bucket Instance](#create-a-bucket-instance) - [oss(options)](#ossoptions) - [Bucket Operations](#bucket-operations) - Base - [.listBuckets(query[, options])](#listbucketsquery-options) - [.putBucket(name[, options])](#putbucketname-options) - [.useBucket(name)](#usebucketname) - [.deleteBucket(name[, options])](#deletebucketname-options) - [.getBucketInfo(name)](#getbucketinfoname) - [.getBucketLocation(name)](#getbucketlocationname) - ACL - [.putBucketACL(name, acl[, options])](#putbucketaclname-acl-options) - [.getBucketACL(name[, options])](#getbucketaclname-options) - Logging - [.putBucketLogging(name, prefix[, options])](#putbucketloggingname-prefix-options) - [.getBucketLogging(name[, options])](#getbucketloggingname-options) - [.deleteBucketLogging(name[, options])](#deletebucketloggingname-options) - Website - [.putBucketWebsite(name, config[, options])](#putbucketwebsitename-config-options) - [.getBucketWebsite(name[, options])](#getbucketwebsitename-options) - [.deleteBucketWebsite(name, region[, options])](#deletebucketwebsitename-options) - Referer - [.putBucketReferer(name, allowEmpty, referers[, options])](#putbucketreferername-allowempty-referers-options) - [.getBucketReferer(name[, options])](#getbucketreferername-options) - [.deleteBucketReferer(name[, options])](#deletebucketreferername-options) - Lifecycle - [.putBucketLifecycle(name, rules[, options])](#putbucketlifecyclename-rules-options) - [.getBucketLifecycle(name[, options])](#getbucketlifecyclename-options) - [.deleteBucketLifecycle(name[, options])](#deletebucketlifecyclename-options) - CORS - [.putBucketCORS(name, rules[, options])](#putbucketcorsname-rules-options) - [.getBucketCORS(name[, options])](#getbucketcorsname-options) - [.deleteBucketCORS(name[, options])](#deletebucketcorsname-options) - RequestPayment - [.getBucketRequestPayment(bucketName[, options])](#getbucketrequestpaymentbucketname-options) - [.putBucketRequestPayment(bucketName, payer[, options])](#putBucketRequestpaymentbucketname-payer-options) - BucketEncryption - [.putBucketEncryption(name[, rules])](#putbucketencryptionname-rules) - [.getBucketEncryption(name)](#getbucketencryptionname) - [.deleteBucketEncryption(name)](#deletebucketencryptionname) - tagging - [.putBucketTags(name, tag[, options])](#putBucketTagsname-tag-options) - [.getBucketTags(name, [, options])](#getBucketTagsname-options) - [.deleteBucketTags(name, [, options])](#deleteBucketTagsname-options) - policy - [.putBucketPolicy(name, policy[, options])](#putBucketPolicyname-policy-options) - [.getBucketPolicy(name, [, options])](#getBucketPolicyname-options) - [.deleteBucketPolicy(name, [, options])](#deleteBucketPolicyname-options) - versioning - [.getBucketVersioning(name, [, options])](#getBucketVersioningname-options) - [.putBucketVersioning(name, status[, options])](#putBucketVersioningname-status-options) - inventory - [.getBucketInventory(name, inventoryId[, options])](#getBucketInventoryname-inventoryid-options) - [.putBucketInventory(name, inventory[, options])](#putBucketInventoryname-inventory-options) - [.deleteBucketInventory(name, inventoryId[, options])](#deleteBucketInventoryname-inventoryid-options) - [.listBucketInventory(name, [, options])](#listBucketInventoryname-options) - worm - [.abortBucketWorm(name[, options])](#abortBucketWormname-options) - [.completeBucketWorm(name, wormId[, options])](#completeBucketWormname-wormId-options) - [.extendBucketWorm(name, wormId, days[, options])](#extendBucketWormname-wormId-days-options) - [.getBucketWorm(name[, options])](#getBucketWormname-options) - [.initiateBucketWorm(name, days[, options])](#initiateBucketWormname-days-options) - [Object Operations](#object-operations) - [.list(query[, options])](#listquery-options) - [.listV2(query[, options])](#listV2query-options) - [.getBucketVersions(query[, options])](#getBucketVersionsquery-options) - [.put(name, file[, options])](#putname-file-options) - [.putStream(name, stream[, options])](#putstreamname-stream-options) - [.append(name, file[, options])](#appendname-file-options) - [.getObjectUrl(name[, baseUrl])](#getobjecturlname-baseurl) - [.generateObjectUrl(name[, baseUrl])](#generateobjecturlname-baseurl) - [.head(name[, options])](#headname-options) - [.getObjectMeta(name[, options])](#getobjectmetaname-options) - [.get(name[, file, options])](#getname-file-options) - [.getStream(name[, options])](#getstreamname-options) - [.delete(name[, options])](#deletename-options) - [.copy(name, sourceName[, sourceBucket, options])](#copyname-sourcename-sourcebucket-options) - [.putMeta(name, meta[, options])](#putmetaname-meta-options) - [.deleteMulti(names[, options])](#deletemultinames-options) - [.signatureUrl(name[, options])](#signatureurlname-options) - [.putACL(name, acl[, options])](#putaclname-acl-options) - [.getACL(name[, options])](#getaclname-options) - [.restore(name[, options])](#restorename-options) - [.putSymlink(name, targetName[, options])](#putsymlinkname-targetname-options) - [.getSymlink(name[, options])](#getsymlinkname-options) - [.initMultipartUpload(name[, options])](#initmultipartuploadname-options) - [.uploadPart(name, uploadId, partNo, file, start, end[, options])](#uploadpartname-uploadid-partno-file-start-end-options) - [.uploadPartCopy(name, uploadId, partNo, range, sourceData[, options])](#uploadpartcopyname-uploadid-partno-range-sourcedata-options) - [.completeMultipartUpload(name, uploadId, parts[, options])](#completemultipartuploadname-uploadid-parts-options) - [.multipartUpload(name, file[, options])](#multipartuploadname-file-options) - [.multipartUploadCopy(name, sourceData[, options])](#multipartuploadcopyname-sourcedata-options) - [.listParts(name, uploadId[, query, options])](#listpartsname-uploadid-query-options) - [.listUploads(query[, options])](#listuploadsquery-options) - [.abortMultipartUpload(name, uploadId[, options])](#abortmultipartuploadname-uploadid-options) - [.calculatePostSignature(policy)](#calculatePostSignaturepolicy) - [.getObjectTagging(name, [, options])](#getObjectTaggingname-options) - [.putObjectTagging(name, tag[, options])](#putObjectTaggingname-tag-options) - [.deleteObjectTagging(name, [, options])](#deleteObjectTaggingname-options) - [RTMP Operations](#rtmp-operations) - [.putChannel(id, conf[, options])](#putchannelid-conf-options) - [.getChannel(id[, options])](#getchannelid-options) - [.deleteChannel(id[, options])](#deletechannelid-options) - [.putChannelStatus(id, status[, options])](#putchannelstatusid-status-options) - [.getChannelStatus(id[, options])](#getchannelstatusid-options) - [.listChannels(query[, options])](#listchannelsquery-options) - [.getChannelHistory(id[, options])](#getchannelhistoryid-options) - [.createVod(id, name, time[, options])](#createvodid-name-time-options) - [.getRtmpUrl(channelId[, options])](#getrtmpurlchannelid-options) - [Create A Image Service Instance](#create-a-image-service-instance) - [oss.ImageClient(options)](#ossimageclientoptions) - [Image Operations](#image-operations) - [imgClient.get(name, file[, options])](#imgclientgetname-file-options) - [imgClient.getStream(name[, options])](#imgclientgetstreamname-options) - [imgClient.getExif(name[, options])](#imgclientgetexifname-options) - [imgClient.getInfo(name[, options])](#imgclientgetinfoname-options) - [imgClient.putStyle(name, style[, options])](#imgclientputstylename-style-options) - [imgClient.getStyle(name[, options])](#imgclientgetstylename-options) - [imgClient.listStyle([options])](#imgclientliststyleoptions) - [imgClient.deleteStyle(name[, options])](#imgclientdeletestylename-options) - [imgClient.signatureUrl(name)](#imgclientsignatureurlname) - [Known Errors](#known-errors) ## Node Usage ### Compatibility - Node: >= 8.0.0 ### Basic usage 1.install SDK using npm ``` npm install ali-oss --save ``` 2.for example: ```js const OSS = require('ali-oss'); const client = new OSS({ region: '<oss region>', accessKeyId: '<Your accessKeyId>', accessKeySecret: '<Your accessKeySecret>', bucket: '<Your bucket name>' }); ``` ## Browser Usage You can use most of the functionalities of `ali-oss` in browser with some exceptions: - put object with streaming: no chunked encoding, we use multipart upload instead - get object to local file: we cannot manipulate file system in browser, we provide signed object url for downloading needs - bucket operations(listBuckets, putBucketLogging, etc) will fail: OSS server currently do not support CORS requests for bucket operations (will probably be fixed later) ### Compatibility - IE >= 10 & Edge - Major versions of Chrome/Firefox/Safari - Major versions of Android/iOS/WP >Note: Because some browsers do not support promises, you need to introduce promise compatible libraries.<br> For example: IE10 and IE11 need to introduce a promise-polyfill. ### Setup #### Bucket setup As browser-side javascript involves CORS operations. You need to setup your bucket CORS rules to allow CORS operations: - set allowed origins to '\*' - allowed methods to 'PUT, GET, POST, DELETE, HEAD' - set allowed headers to '\*' - expose 'ETag' in expose headers #### STS setup As we don't want to expose the accessKeyId/accessKeySecret in the browser, a [common practice][oss-sts] is to use STS to grant temporary access. ### Basic usage Include the sdk lib in the `<script>` tag and you have `OSS` available for creating client. ```html // x.x.x The specific version number represented // we recommend introducing offline resources, because the usability of online resources depends on the stability of the cdn server. <!-- Introducing online resources --> <script src="http://gosspublic.alicdn.com/aliyun-oss-sdk-x.x.x.min.js"></script> <!-- Introducing offline resources --> <script src="./aliyun-oss-sdk-x.x.x.min.js"></script> <script type="text/javascript"> const client = new OSS({ region: 'oss-cn-hangzhou', accessKeyId: '<access-key-id>', accessKeySecret: '<access-key-secret>', bucket: '<bucket-name>', stsToken: '<security-token>' }); client.list().then((result) => { console.log('objects: %j', result.objects); return client.put('my-obj', new OSS.Buffer('hello world')); }).then((result) => { console.log('put result: %j', result); return client.get('my-obj'); }).then((result) => { console.log('get result: %j', result.content.toString()); }); </script> ``` The full sample can be found [here][browser-sample]. ### How to build ```bash npm run build-dist ``` And see the build artifacts under `dist/`. ## Data Regions [OSS current data regions](https://help.aliyun.com/document_detail/31837.html). region | country | city | endpoint | internal endpoint --- | --- | --- | --- | --- oss-cn-hangzhou | China | HangZhou | oss-cn-hangzhou.aliyuncs.com | oss-cn-hangzhou-internal.aliyuncs.com oss-cn-shanghai | China | ShangHai | oss-cn-shanghai.aliyuncs.com | oss-cn-shanghai-internal.aliyuncs.com oss-cn-qingdao | China | QingDao | oss-cn-qingdao.aliyuncs.com | oss-cn-qingdao-internal.aliyuncs.com oss-cn-beijing | China | BeiJing | oss-cn-beijing.aliyuncs.com | oss-cn-beijing-internal.aliyuncs.com oss-cn-shenzhen | China | ShenZhen | oss-cn-shenzhen.aliyuncs.com | oss-cn-shenzhen-internal.aliyuncs.com oss-cn-hongkong | China | HongKong | oss-cn-hongkong.aliyuncs.com | oss-cn-hongkong-internal.aliyuncs.com oss-us-west-1 | US | Silicon Valley | oss-us-west-1.aliyuncs.com | oss-us-west-1-internal.aliyuncs.com oss-ap-southeast-1 | Singapore | Singapore | oss-ap-southeast-1.aliyuncs.com | oss-ap-southeast-1-internal.aliyuncs.com ## Create Account Go to [OSS website](http://www.aliyun.com/product/oss/?lang=en), create a new account for new user. After account created, you can create the OSS instance and get the `accessKeyId` and `accessKeySecret`. ## Create A Bucket Instance Each OSS instance required `accessKeyId`, `accessKeySecret` and `bucket`. ## oss(options) Create a Bucket store instance. options: - accessKeyId {String} access key you create on aliyun console website - accessKeySecret {String} access secret you create - [stsToken] {String} used by temporary authorization, detail [see](https://www.alibabacloud.com/help/doc-detail/32077.htm) - [refreshSTSToken] {Function} used by auto set `stsToken`、`accessKeyId`、`accessKeySecret` when sts info expires. return value must be object contains `stsToken`、`accessKeyId`、`accessKeySecret` - [refreshSTSTokenInterval] {number} use time (ms) of refresh STSToken interval it should be less than sts info expire interval, default is 300000ms(5min) when sts info expires. return value must be object contains `stsToken`、`accessKeyId`、`accessKeySecret` - [bucket] {String} the default bucket you want to access If you don't have any bucket, please use `putBucket()` create one first. - [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) - [region] {String} the bucket data region location, please see [Data Regions](#data-regions), default is `oss-cn-hangzhou`. - [internal] {Boolean} access OSS with aliyun internal network or not, default is `false`. If your servers are running on aliyun too, you can set `true` to save lot of money. - [secure] {Boolean} instruct OSS client to use HTTPS (secure: true) or HTTP (secure: false) protocol. - [timeout] {String|Number} instance level timeout for all operations, default is `60s`. - [cname] {Boolean}, default false, access oss with custom domain name. if true, you can fill `endpoint` field with your custom domain name, - [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. the details you can see [requestPay](https://help.aliyun.com/document_detail/91337.htm) - [useFetch] {Boolean}, default false, it just work in Browser, if true,it means upload object with `fetch` mode ,else `XMLHttpRequest` - [enableProxy] {Boolean}, Enable proxy request, default is false. - [proxy] {String | Object}, proxy agent uri or options, default is null. - [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 - [maxSockets] {Number} Maximum number of sockets to allow per host. Default is infinity example: 1. basic usage ```js const OSS = require('ali-oss'); const store = new OSS({ accessKeyId: 'your access key', accessKeySecret: 'your access secret', bucket: 'your bucket name', region: 'oss-cn-hangzhou' }); ``` 2. use accelerate endpoint - Global accelerate endpoint: oss-accelerate.aliyuncs.com - Accelerate endpoint of regions outside mainland China: oss-accelerate-overseas.aliyuncs.com ```js const OSS = require('ali-oss'); const store = new OSS({ accessKeyId: 'your access key', accessKeySecret: 'your access secret', bucket: 'your bucket name', endpoint: 'oss-accelerate.aliyuncs.com', }); ``` 3. use custom domain ```js const OSS = require('ali-oss'); const store = new OSS({ accessKeyId: 'your access key', accessKeySecret: 'your access secret', cname: true, endpoint: 'your custome domain', }); ``` 4. use STS and refreshSTSToken ```js const OSS = require('ali-oss'); const store = new OSS({ accessKeyId: 'your STS key', accessKeySecret: 'your STS secret', stsToken: 'your STS token', refreshSTSToken: async () => { const info = await fetch('you sts server'); return { accessKeyId: info.accessKeyId, accessKeySecret: info.accessKeySecret, stsToken: info.stsToken } }, refreshSTSTokenInterval: 300000 }); ``` 5. retry request with stream ```js for (let i = 0; i <= store.options.retryMax; i++) { try { const result = await store.putStream("<example-object>", fs.createReadStream("<example-path>")); console.log(result); break; // break if success } catch (e) { console.log(e); } } ``` ## Bucket Operations ### .listBuckets(query[, options]) List buckets in this account. parameters: - [query] {Object} query parameters, default is `null` - [prefix] {String} search buckets using `prefix` key - [marker] {String} search start from `marker`, including `marker` key - [max-keys] {String|Number} max buckets, default is `100`, limit to `1000` - [options] {Object} optional parameters - [timeout] {Number} the operation timeout Success will return buckets list on `buckets` properties. - buckets {Array<BucketMeta>} bucket meta info list Each `BucketMeta` will contains blow properties: - name {String} bucket name - region {String} bucket store data region, e.g.: `oss-cn-hangzhou-a` - creationDate {String} bucket create GMT date, e.g.: `2015-02-19T08:39:44.000Z` - storageClass {String} e.g.: `Standard`, `IA`, `Archive` - owner {Object} object owner, including `id` and `displayName` - isTruncated {Boolean} truncate or not - nextMarker {String} next marker string - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) example: - List top 10 buckets ```js store.listBuckets({ "max-keys": 10 }).then((result) => { console.log(result); }); ``` ### .putBucket(name[, options]) Create a new bucket. parameters: - name {String} bucket name If bucket exists and not belong to current account, will throw BucketAlreadyExistsError. If bucket not exists, will create a new bucket and set it's ACL. - [options] {Object} optional parameters - [acl] {String} include `private`,`public-read`,`public-read-write` - [storageClass] {String} the storage type include (Standard,IA,Archive) - [dataRedundancyType] {String} default `LRS`, include `LRS`,`ZRS` - [timeout] {Number} the operation timeout Success will return the bucket name on `bucket` properties. - bucket {String} bucket name - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) example: - Create a bucket name `helloworld` location on HongKong ```js store.putBucket('helloworld').then((result) => { // use it by default store.useBucket('helloworld'); }); ``` - Create a bucket name `helloworld` location on HongKong StorageClass `Archive` ```js await store.putBucket('helloworld', { StorageClass: 'Archive' }); // use it by default store.useBucket('helloworld'); ``` ### .deleteBucket(name[, options]) Delete an empty bucket. parameters: - name {String} bucket name If bucket is not empty, will throw BucketNotEmptyError. If bucket is not exists, will throw NoSuchBucketError. - [options] {Object} optional parameters - [timeout] {Number} the operation timeout Success will return: - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) example: - Delete the exists 'helloworld' bucket on 'oss-cn-hongkong' ```js store.deleteBucket('helloworld').then((result) => {}); ``` ### .useBucket(name) Use the bucket. parameters: - name {String} bucket name example: - Use `helloworld` as the default bucket ```js store.useBucket('helloworld'); ``` ### .getBucketInfo(name) Get bucket information,include CreationDate、ExtranetEndpoint、IntranetEndpoint、Location、Name、StorageClass、 Owner、AccessControlList、Versioning parameters: - name {String} bucket name example: - Use `helloworld` as the default bucket ```js store.getBucketInfo('helloworld').then( (res) => { console.log(res.bucket) }) ``` ### .getBucketLocation(name) Get bucket location parameters: - name {String} bucket name example: - Use `helloworld` as the default bucket ```js store.getBucketLocation('helloworld').then( (res) => { console.log(res.location) }) ``` --- ### .putBucketACL(name, acl[, options]) Update the bucket ACL. parameters: - name {String} bucket name - acl {String} access control list, current available: `public-read-write`, `public-read` and `private` - [options] {Object} optional parameters - [timeout] {Number} the operation timeout Success will return: - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) example: - Set bucket `helloworld` to `public-read-write` ```js store.putBucketACL('helloworld', 'public-read-write').then((result) => { }); ``` ### .getBucketACL(name[, options]) Get the bucket ACL. parameters: - name {String} bucket name - [options] {Object} optional parameters - [timeout] {Number} the operation timeout Success will return: - acl {String} acl settiongs string - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) example: - Get bucket `helloworld` ```js store.getBucketACL('helloworld').then((result) => { console.log(result.acl); }); ``` --- ### .putBucketLogging(name, prefix[, options]) Update the bucket logging settings. Log file will create every one hour and name format: `<prefix><bucket>-YYYY-mm-DD-HH-MM-SS-UniqueString`. parameters: - name {String} bucket name - [prefix] {String} prefix path name to store the log files - [options] {Object} optional parameters - [timeout] {Number} the operation timeout Success will return: - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) example: - Enable bucket `helloworld` logging and save with prefix `logs/` ```js store.putBucketLogging('helloworld', 'logs/').then((result) => { }); ``` ### .getBucketLogging(name[, options]) Get the bucket logging settings. parameters: - name {String} bucket name - [options] {Object} optional parameters - [timeout] {Number} the operation timeout Success will return: - enable {Boolean} enable logging or not - prefix {String} prefix path name to store the log files, maybe `null` - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) example: - Get bucket `helloworld` logging settings ```js store.getBucketLogging('helloworld').then((result) => { console.log(result.enable, result.prefix); }); ``` ### .deleteBucketLogging(name[, options]) Delete the bucket logging settings. parameters: - name {String} bucket name - [options] {Object} optional parameters - [timeout] {Number} the operation timeout Success will return: - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) --- ### .putBucketWebsite(name, config[, options]) Set the bucket as a static website. parameters: - name {String} bucket name - config {Object} website config, contains blow properties: - index {String} default page, e.g.: `index.html` - [error] {String} error page, e.g.: 'error.html' - [supportSubDir] {String} default vaule false - [type] {String} default value 0 - [routingRules] {Array} RoutingRules - [options] {Object} optional parameters - [timeout] {Number} the operation timeout Success will return: - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) example: ```js store.putBucketWebsite('hello', { index: 'index.html' }).then((result) => { }); ``` ### .getBucketWebsite(name[, options]) Get the bucket website config. parameters: - name {String} bucket name - [options] {Object} optional parameters - [timeout] {Number} the operation timeout Success will return: - index {String} index page - error {String} error page, maybe `null` - supportSubDir {String} - type {String} - routingRules {Array} - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) ### .deleteBucketWebsite(name[, options]) Delete the bucket website config. parameters: - name {String} bucket name - [options] {Object} optional parameters - [timeout] {Number} the operation timeout Success will return: - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) --- ### .putBucketReferer(name, allowEmpty, referers[, options]) Set the bucket request `Referer` white list. parameters: - name {String} bucket name - allowEmpty {Boolean} allow empty request referer or not - referers {Array<String>} `Referer` white list, e.g.: ```js [ 'https://npm.taobao.org', 'http://cnpmjs.org' ] ``` - [options] {Object} optional parameters - [timeout] {Number} the operation timeout Success will return: - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) example: ```js store.putBucketReferer('hello', false, [ 'https://npm.taobao.org', 'http://cnpmjs.org' ]).then((result) => { }); ``` ### .getBucketReferer(name[, options]) Get the bucket request `Referer` white list. parameters: - name {String} bucket name - [options] {Object} optional parameters - [timeout] {Number} the operation timeout Success will return: - allowEmpty {Boolean} allow empty request referer or not - referers {Array<String>} `Referer` white list - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) ### .deleteBucketReferer(name[, options]) Delete the bucket request `Referer` white list. parameters: - name {String} bucket name - [options] {Object} optional parameters - [timeout] {Number} the operation timeout Success will return: - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) --- ### .putBucketLifecycle(name, rules[, options]) Set the bucket object lifecycle. parameters: - name {String} bucket name - rules {Array<Rule>} rule config list, each `Rule` will contains blow properties: - [id] {String} rule id, if not set, OSS will auto create it with random string. - prefix {String} store prefix - status {String} rule status, allow values: `Enabled` or `Disabled` - [expiration] {Object} specifies the expiration attribute of the lifecycle rules for the object. - [days] {Number|String} expire after the `days` - [createdBeforeDate] {String} expire date, e.g.: `2022-10-11T00:00:00.000Z` - [expiredObjectDeleteMarker] {String} value `true` `createdBeforeDate` and `days` and `expiredObjectDeleteMarker` must have one. - [abortMultipartUpload] {Object} Specifies the expiration attribute of the multipart upload tasks that are not complete. - [days] {Number|String} expire after the `days` - [createdBeforeDate] {String} expire date, e.g.: `2022-10-11T00:00:00.000Z` `createdBeforeDate` and `days` must have one. - [transition] {Object} Specifies the time when an object is converted to the IA or archive storage class during a valid life cycle. - storageClass {String} Specifies the storage class that objects that conform to the rule are converted into. allow values: `IA` or `Archive` - [days] {Number|String} expire after the `days` - [createdBeforeDate] {String} expire date, e.g.: `2022-10-11T00:00:00.000Z` `createdBeforeDate` and `days` must have one. - [noncurrentVersionTransition] {Object} Specifies the time when an object is converted to the IA or archive storage class during a valid life cycle. - storageClass {String} Specifies the storage class that history objects that conform to the rule are converted into. allow values: `IA` or `Archive` - noncurrentDays {String} expire after the `noncurrentDays` `expiration`、 `abortMultipartUpload`、 `transition`、 `noncurrentVersionTransition` must have one. - [noncurrentVersionExpiration] {Object} specifies the expiration attribute of the lifecycle rules for the history object. - noncurrentDays {String} expire after the `noncurrentDays` - [tag] {Object} Specifies the object tag applicable to a rule. Multiple tags are supported. - key {String} Indicates the tag key. - value {String} Indicates the tag value. `tag` cannot be used with `abortMultipartUpload` - [options] {Object} optional parameters - [timeout] {Number} the operation timeout Success will return: - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) example: ```js store.putBucketLifecycle('hello', [ { id: 'delete after one day', prefix: 'logs/', status: 'Enabled', days: 1 }, { prefix: 'logs2/', status: 'Disabled', date: '2022-10-11T00:00:00.000Z' } ]).then((result) => {}); ``` example: for history with noncurrentVersionExpiration ```js const result = await store.putBucketLifecycle(bucket, [{ id: 'expiration1', prefix: 'logs/', status: 'Enabled', expiration: { days: '1' }, noncurrentVersionExpiration: { noncurrentDays: '1' } }]); console.log(result) ``` example: for history with expiredObjectDeleteMarker ```js const result = await store.putBucketLifecycle(bucket, [{ id: 'expiration1', prefix: 'logs/', status: 'Enabled', expiration: { expiredObjectDeleteMarker: 'true' }, noncurrentVersionExpiration: { noncurrentDays: '1' } }]); console.log(result) ``` example: for history with noncurrentVersionTransition ```js const result = await store.putBucketLifecycle(bucket, [{ id: 'expiration1', prefix: 'logs/', status: 'Enabled', noncurrentVersionTransition: { noncurrentDays: '10', storageClass: 'IA' } }]); console.log(result) ``` ### .getBucketLifecycle(name[, options]) Get the bucket object lifecycle. parameters: - name {String} bucket name - [options] {Object} optional parameters - [timeout] {Number} the operation timeout Success will return: - rules {Array<Rule>} the lifecycle rule list - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) ### .deleteBucketLifecycle(name[, options]) Delete the bucket object lifecycle. parameters: - name {String} bucket name - [options] {Object} optional parameters - [timeout] {Number} the operation timeout Success will return: - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) --- ### .putBucketCORS(name, rules[, options]) Set CORS rules of the bucket object parameters: - name {String} bucket name - rules {Array<Rule>} rule config list, each `Rule` will contains below properties: - allowedOrigin {String/Array} configure for Access-Control-Allow-Origin header - allowedMethod {String/Array} configure for Access-Control-Allow-Methods header - [allowedHeader] {String/Array} configure for Access-Control-Allow-Headers header - [exposeHeader] {String/Array} configure for Access-Control-Expose-Headers header - [maxAgeSeconds] {String} configure for Access-Control-Max-Age header - [options] {Object} optional parameters - [timeout] {Number} the operation timeout Success will return: - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) example: ```js store.putBucketCORS('hello', [ { allowedOrigin: '*', allowedMethod: [ 'GET', 'HEAD', ], } ]).then((result) => {}); ``` ### .getBucketCORS(name[, options]) Get CORS rules of the bucket object. parameters: - name {String} bucket name - [options] {Object} optional parameters - [timeout] {Number} the operation timeout Success will return: - rules {Array<Rule>} the CORS rule list - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) ### .deleteBucketCORS(name[, options]) Delete CORS rules of the bucket object. parameters: - name {String} bucket name - [options] {Object} optional parameters - [timeout] {Number} the operation timeout Success will return: - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) ### .getBucketRequestPayment(bucketName[, options]) get RequestPayment value of the bucket object. parameters: - bucketName {String} bucket name - [options] {Object} optional parameters Success will return: - status {Number} response status - payer {String} payer, BucketOwner or Requester - res {Object} response info, including - data {Buffer} xml --- ### .putBucketRequestPayment(bucketName, payer[, options]) put RequestPayment value of the bucket object. parameters: - bucketName {String} - payer {String} payer - [options] {Object} optional parameters Success will return: - status {Number} response status - res {Object} response info --- ### .putBucketEncryption(name, rules) put BucketEncryption value of the bucket object. parameters: - name {String} bucket name - [rules] {Object} parameters - SSEAlgorithm {String} encryption type, expect AES256 or KMS - {KMSMasterKeyID} {String} needed when encryption type is KMS Success will return: - status {Number} response status - res {Object} response info --- ### .getBucketEncryption(name) get BucketEncryption rule value of the bucket object. parameters: - name {String} bucket name Success will return: - status {Number} response status - res {Object} response info - encryption {Object} rules - SSEAlgorithm {String} encryption type, AES256 or KMS - {KMSMasterKeyID} {String} will be return when encryption type is KMS --- ### .deleteBucketEncryption(name) delete BucketEncryption rule value of the bucket object. parameters: - name {String} bucket name Success will return: - status {Number} response status - res {Object} response info --- ### .putBucketTags(name, tag[, options]) Adds tags for a bucket or modify the tags for a bucket. parameters: - name {String} the object name - tag {Object} tag, eg. `{var1: value1,var2:value2}` - [options] {Object} optional args Success will return: - status {Number} response status - res {Object} response info --- ### .getBucketTags(name[, options]) Obtains the tags for a bucket. parameters: - name {String} the object name - [options] {Object} optional args Success will return: - tag {Object} the tag of object - res {Object} response info --- ### .deleteBucketTags(name[, options]) Deletes the tags added for a bucket. parameters: - name {String} the object name - [options] {Object} optional args Success will return: - status {Number} response status - res {Object} response info --- ### .putBucketPolicy(name, policy[, options]) Adds or modify policy for a bucket. parameters: - name {String} the bucket name - policy {Object} bucket policy - [options] {Object} optional args Success will return: - status {Number} response status - res {Object} response info example: ```js const policy = { Version: '1', Statement: [ { Action: ['oss:PutObject', 'oss:GetObject'], Effect: 'Deny', Principal: ['1234567890'], Resource: ['acs:oss:*:1234567890:*/*'] } ] }; const result = await store.putBucketPolicy(bucket, policy); console.log(result); ``` --- ### .getBucketPolicy(name[, options]) Obtains the policy for a bucket. parameters: - name {String} the bucket name - [options] {Object} optional args Success will return: - policy {Object} the policy of bucket, if not exist, the value is null - res {Object} response info - status {Number} response status --- ### .deleteBucketPolicy(name[, options]) Deletes the policy added for a bucket. parameters: - name {String} the bucket name - [options] {Object} optional args Success will return: - status {Number} response status - res {Object} response info --- ### .getBucketVersioning(name[, options]) Obtains the version status of an object parameters: - name {String} the bucket name - [options] {Object} optional args Success will return: - status {Number} response status - versionStatus {String | undefined} version status, `Suspended` or `Enabled`. default value: `undefined` - res {Object} response info --- ### .putBucketVersioning(name, status[, options]) set the version status of an object parameters: - name {String} the bucket name - status {String} version status, allow values: `Enabled` or `Suspended` - [options] {Object} optional args Success will return: - status {Number} response status - res {Object} response info --- ### .getBucketInventory(name, inventoryId[, options]) get bucket inventory by inventory-id parameters: - name {String} the bucket name - inventoryId {String} inventory-id - [options] {Object} optional args Success will return: - inventory {Inventory} - status {Number} response status - res {Object} response info ```js async function getBucketInventoryById() { try { const result = await client.getBucketInventory('bucket', 'inventoryid'); console.log(result.inventory) } catch (err) { console.log(err) } } getBucketInventoryById(); ``` ### putBucketInventory(name, inventory[, options]) set bucket inventory parameters: - name {String} the bucket name - inventory {Inventory} inventory config - [options] {Object} optional args Success will return: - status {Number} response status - res {Object} response info ```ts type Field = 'Size | LastModifiedDate | ETag | StorageClass | IsMultipartUploaded | EncryptionStatus'; interface Inventory { id: string; isEnabled: true | false; prefix?: string; OSSBucketDestination: { format: 'CSV'; accountId: string; rolename: string; bucket: string; prefix?: string; encryption?: | {'SSE-OSS': ''} | { 'SSE-KMS': { keyId: string; }; }; }; frequency: 'Daily' | 'Weekly'; includedObjectVersions: 'Current' | 'All'; optionalFields?: { field?: Field[]; }; } ``` ```js const inventory = { id: 'default', isEnabled: false, // `true` | `false` prefix: 'ttt', // filter prefix OSSBucketDestination: { format: 'CSV', accountId: '1817184078010220', rolename: 'AliyunOSSRole', bucket: 'your bucket', prefix: 'test', //encryption: {'SSE-OSS': ''}, /* encryption: { 'SSE-KMS': { keyId: 'test-kms-id'; };, */ }, frequency: 'Daily', // `WEEKLY` | `Daily` includedObjectVersions: 'All', // `All` | `Current` optionalFields: { field: ["Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "EncryptionStatus"] }, } async function putInventory(){ const bucket = 'Your Bucket Name'; try { await client.putBucketInventory(bucket, inventory); } catch(err) { console.log(err); } } putInventory() ``` ### deleteBucketInventory(name, inventoryId[, options]) delete bucket inventory by inventory-id parameters: - name {String} the bucket name - inventoryId {String} inventory-id - [options] {Object} optional args Success will return: - status {Number} response status - res {Object} response info ### listBucketInventory(name[, options]) list bucket inventory parameters: - name {String} the bucket name - [options] {Object} optional args - continuationToken used by search next page Success will return: - status {Number} response status - res {Object} response info example: ```js async function listBucketInventory() { const bucket = 'Your Bucket Name'; let nextContinuationToken; // list all inventory of the bucket do { const result = await client.listBucketInventory(bucket, nextContinuationToken); console.log(result.inventoryList); nextContinuationToken = result.nextContinuationToken; } while (nextContinuationToken) } listBucketInventory(); ``` ### .abortBucketWorm(name[, options]) used to delete an unlocked retention policy. parameters: - name {String} the bucket name - [options] {Object} optional args Success will return: - status {Number} response status - res {Object} response info --- ### .completeBucketWorm(name, wormId[, options]) used to lock a retention policy. parameters: - name {String} the bucket name - wormId {String} worm id - [options] {Object} optional args Success will return: - status {Number} response status - res {Object} response info --- ### .extendBucketWorm(name, wormId, days[, options]) used to extend the retention period of objects in a bucket whose retention policy is locked. parameters: - name {String} the bucket name - wormId {String} worm id - days {String | Number} retention days - [options] {Object} optional args Success will return: - status {Number} response status - res {Object} response info --- ### .getBucketWorm(name[, options]) used to query the retention policy information of the specified bucket. parameters: - name {String} the bucket name - [options] {Object} optional args Success will return: - wormId {String} worm id - state {String} `Locked` or `InProgress` - days {String} retention days - creationDate {String} - status {Number} response status - res {Object} response info --- ### .initiateBucketWorm(name, days[, options]) create a retention policy. parameters: - name {String} the bucket name - days {String | Number}} set retention days - [options] {Object} optional args Success will return: - wormId {String} worm id - status {Number} response status - res {Object} response info --- ## Object Operations All operations function return Promise, except `signatureUrl`. ### .put(name, file[, options]) Add an object to the bucket. parameters: - name {String} object name store on OSS - 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 - [options] {Object} optional parameters - [timeout] {Number} the operation timeout - [mime] {String} custom mime, will send with `Content-Type` entity header - [meta] {Object} user meta, will send with `x-oss-meta-` prefix string e.g.: `{ uid: 123, pid: 110 }` - [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> - url {String} After a file is uploaded successfully, the OSS sends a callback request to this URL. - [host] {String} The host header value for initiating callback requests. - body {String} The value of the request body when a callback is initiated, for example, key=$(key)&etag=$(etag)&my_var=$(x:my_var). - [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. - [customValue] {Object} Custom parameters are a map of key-values<br> e.g.: ```js var customValue = {var1: 'value1', var2: 'value2'} ``` - [headers] {Object} extra headers - 'Cache-Control' cache control for download, e.g.: `Cache-Control: public, no-cache` - 'Content-Disposition' object name for download, e.g.: `Content-Disposition: somename` - 'Content-Encoding' object content encoding for download, e.g.: `Content-Encoding: gzip` - 'Expires' expires time for download, an absolute date and time. e.g.: `Tue, 08 Dec 2020 13:49:43 GMT` - See more: [PutObject](https://help.aliyun.com/document_detail/31978.html#title-yxe-96d-x61) - [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 Success will return the object information. object: - name {String} object name - data {Object} callback server response data, sdk use JSON.parse() return - res {Object} response info, including - status {Number} response status - headers {Object} response headers - size {Number} response size - rt {Number} request total use time (ms) example: - Add an object through local file path ```js const filepath = '/home/ossdemo/demo.txt'; store.put('ossdemo/demo.txt', filepath).then((result) => { console.log(result); }); { name: 'ossdemo/demo.txt', res: { status: 200, headers: { date: 'Tue, 17 Feb 2015 13:28:17 GMT', 'content-length': '0', connection: 'close', etag: '"BF7A03DA01440845BC5D487B369BC168"', server: 'AliyunOSS', 'x-oss-request-id': '54E341F1707AA0275E829244' }, size: 0, rt: 92 } } ``` - Add an object through content buffer ```js store.put('ossdemo/buffer', Buffer.from('foo content')).then((result) => { console.log(result); }); { name: 'ossdemo/buffer', url: 'http://demo.oss-cn-hangzhou.aliyuncs.com/ossdemo/buffer', res: { status: 200, headers: { date: 'Tue, 17 Feb 2015 13:28:17 GMT', 'content-length': '0', connection: 'close', etag: '"xxx"', server: 'AliyunOSS', 'x-oss-request-id': '54E341F1707AA0275E829243' }, size: 0, rt: 92 } } ``` - Add an object through readstream ```js const filepath = '/home/ossdemo/demo.txt'; store.put('ossdemo/readstream.txt', fs.createReadStream(filepath)).then((result) => { console.log(result); }); { name: 'ossdemo/readstream.txt', url: 'http://demo.oss-cn-hangzhou.aliyuncs.com/ossdemo/readstream.txt', res: { status: 200, headers: { date: 'Tue, 17 Feb 2015 13:28:17 GMT', 'content-length': '0', connection: 'close', etag: '"BF7A03DA01440845BC5D487B369BC168"', server: 'AliyunOSS', 'x-oss-request-id': '54E341F1707AA0275E829242' }, size: 0, rt: 92 } } ``` ### .putStream(name, stream[, options]) Add a stream object to the bucket. parameters: - name {String} object name store on OSS - stream {ReadStream} object ReadStream content instance - [options] {Object} optional parameters - [contentLength] {Number} the stream length, `chunked encoding` will be used if absent - [timeout] {Number} the operation timeout - [mime] {String} custom mime, will send with `Content-Type` entity header - [meta] {Object} user meta, will send with `x-oss-meta-` prefix string e.g.: `{ uid: 123, pid: