Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

ali-oss

ali-sdk222.7kMIT6.22.0TypeScript support: included

aliyun oss(object storage service) node client

oss, client, file, aliyun

readme

oss-js-sdk

NPM version build status coverage David deps

aliyun OSS(Object Storage Service) js client for Node and Browser env.

NOTE: For SDK 5.X document, please go to README.md

Install

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, if you want to see more practices ,please refer to Web Post

QA

Please log in to the official website and contact technical support.

License

MIT

OSS Usage

OSS, Object Storage Service. Equal to well known Amazon S3.

All operation use es7 async/await to implement. All api is async function.

Summary

Node Usage

Compatibility

  • Node: >= 8.0.0

Basic usage

1.install SDK using npm

npm install ali-oss --save

2.for example:

const OSS = require('ali-oss');
const store = 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.
    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.

// 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 store = new OSS({
    region: 'oss-cn-hangzhou',
    accessKeyId: '<access-key-id>',
    accessKeySecret: '<access-key-secret>',
    bucket: '<bucket-name>',
    stsToken: '<security-token>'
  });

  store
    .list()
    .then(result => {
      console.log('objects: %j', result.objects);
      return store.put('my-obj', new OSS.Buffer('hello world'));
    })
    .then(result => {
      console.log('put result: %j', result);
      return store.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

npm run build-dist

And see the build artifacts under dist/.

Data Regions

OSS current data regions.

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, 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
  • [refreshSTSToken] {Function} used by auto set stsTokenaccessKeyIdaccessKeySecret when sts info expires. return value must be object contains stsTokenaccessKeyIdaccessKeySecret
  • [refreshSTSTokenInterval] {number} use time (ms) of refresh STSToken interval it should be less than sts info expire interval, default is 300000ms(5min)
  • [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
  • [region] {String} the bucket data region location, please see 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 a 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
  • [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. NOTE: When enabling proxy request, please ensure that proxy-agent is installed.
  • [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
  • [authorizationV4] {Boolean} Use V4 signature. Default is false.

example:

  1. basic usage
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'
});
  1. use accelerate endpoint

  2. Global accelerate endpoint: oss-accelerate.aliyuncs.com

  3. Accelerate endpoint of regions outside mainland China: oss-accelerate-overseas.aliyuncs.com
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'
});
  1. use custom domain
const OSS = require('ali-oss');

const store = new OSS({
  accessKeyId: 'your access key',
  accessKeySecret: 'your access secret',
  cname: true,
  endpoint: 'your custome domain'
});
  1. use STS and refreshSTSToken
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
});
  1. retry request with stream
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);
  }
}
  1. 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.
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',
  authorizationV4: true
});

try {
  const bucketInfo = await store.getBucketInfo('your bucket name');
  console.log(bucketInfo);
} catch (e) {
  console.log(e);
}

try {
  const putObjectResult = await store.put('your bucket name', 'your object name', {
    headers: {
      // The headers of this request
      header1: 'value1',
      header2: 'value2'
    },
    // 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.
    additionalHeaders: ['additional header1', 'additional header2']
  });
  console.log(putObjectResult);
} 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
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
store.putBucket('helloworld').then(result => {
  // use it by default
  store.useBucket('helloworld');
});
  • Create a bucket name helloworld location on HongKong StorageClass Archive
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'
store.deleteBucket('helloworld').then(result => {});

.useBucket(name)

Use the bucket.

parameters:

  • name {String} bucket name

example:

  • Use helloworld as the default bucket
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
store.getBucketInfo('helloworld').then(res => {
  console.log(res.bucket);
});

.getBucketStat(name)

Call the GetBucketStat interface to get the storage capacity of the specified storage space (Bucket) and the number of files (Object).

Calling this interface requires the oss:GetBucketStat permission. The data obtained by calling this interface is not real-time data and may be delayed for more than an hour. 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.

parameters:

  • name {String} bucket name

Success will return:

  • stat {Object} container for the BucketStat structure:

    • Storage {String} the total storage capacity of the Bucket, in bytes.
    • ObjectCount {String} total number of Objects in the Bucket。
    • MultipartUploadCount {String} the number of Multipart Uploads in the Bucket that have been initialized but not yet completed (Complete) or not yet aborted (Abort).
    • LiveChannelCount {String} the number of Live Channels in the Bucket.
    • LastModifiedTime {String} the point in time, in timestamps, when the storage information was retrieved.
    • StandardStorage {String} the amount of storage of the standard storage type, in bytes.
    • StandardObjectCount {String} the number of objects of the standard storage type.
    • InfrequentAccessStorage {String} the amount of billed storage for the low-frequency storage type, in bytes.
    • InfrequentAccessRealStorage {String} the actual storage amount of the low-frequency storage type, in bytes.
    • InfrequentAccessObjectCount {String} the number of Objects of the low-frequency storage type.
    • ArchiveStorage {String} the amount of billed storage for the archive storage type, in bytes.
    • ArchiveRealStorage {String} the actual storage amount of the archive storage type, in bytes.
    • ArchiveObjectCount {String} the number of objects of the archive storage type.
    • ColdArchiveStorage {String} the amount of billed storage for the cold archive storage type, in bytes.
    • ColdArchiveRealStorage {String} the actual storage amount in bytes for the cold archive storage type.
    • ColdArchiveObjectCount {String} the number of objects of the cold archive storage type.
  • 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:

  • If you don't fill in the name, the default is the bucket defined during initialization.
store.getBucketStat().then(res => console.log(res));

.getBucketLocation(name)

Get bucket location

parameters:

  • name {String} bucket name

example:

  • Use helloworld as the default bucket
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
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
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/
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
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:

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.:
    ['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:

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 or ColdArchive or DeepColdArchive
      • [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 or ColdArchive or DeepColdArchive
      • noncurrentDays {String} expire after the noncurrentDays expirationabortMultipartUploadtransitionnoncurrentVersionTransition 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:

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

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

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

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:

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:

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
async function getBucketInventoryById() {
  try {
    const result = await store.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
type Field =
  'Size | LastModifiedDate | ETag | StorageClass | IsMultipartUploaded | EncryptionStatus | ObjectAcl | TaggingCount | ObjectType | Crc64';
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[];
  };
}
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',
      'ObjectAcl',
      'TaggingCount',
      'ObjectType',
      'Crc64'
    ]
  }
};

async function putInventory() {
  const bucket = 'Your Bucket Name';
  try {
    await store.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:

async function listBucketInventory() {
  const bucket = 'Your Bucket Name';
  let nextContinuationToken;
  // list all inventory of the bucket
  do {
    const result = await store.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 (ms)
    • [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
      • 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.
      • [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.
      • [customValue] {Object} Custom parameters are a map of key-values
        e.g.:
        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
    • [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
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
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
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: 110 }
    • [callback] {Object} The callback parameter is composed of a JSON string encoded in Base64,detail see
      • 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.
      • [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.
      • [customValue] {Object} Custom parameters are a map of key-values
        e.g.:
        var customValue = { var1: 'value1', var2: 'value2' };
    • [headers] {Object} extra headers, detail see RFC 2616
      • '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

Success will return the object information.

object:

  • name {String} object 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:

  • Add an object through readstream
const filepath = '/home/ossdemo/demo.txt';
store.putStream('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
//   }
// }

.append(name, file[, options])

Append an object to the bucket, it's almost same as put, but it can add content to existing object rather than override it.

All parameters are same as put except for options.position

  • name {String} object name store on OSS
  • file {String|Buffer|ReadStream} object local path, content buffer or ReadStream content instance
  • [options] {Object} optional parameters
    • [position] {String} specify the position which is the content length of the latest object
    • [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 }
    • [headers] {Object} extra headers, detail see RFC 2616
      • '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

object:

  • name {String} object name
  • url {String} the url of oss
  • res {Object} response info, including
    • status {Number} response status
    • headers {Object} response headers
    • size {Number} response size
    • rt {Number} request total use time (ms)
  • nextAppendPosition {String} the next position(The browser needs to set cross domain and expose the x-oss-next-append-position header)

example:

let object = await store.append('ossdemo/buffer', Buffer.from('foo'));

// append content to the existing object
object = await store.append('ossdemo/buffer', Buffer.from('bar'), {
  position: object.nextAppendPosition
});

.getObjectUrl(name[, baseUrl])

Get the Object url. If provide baseUrl, will use baseUrl instead the default endpoint.

e.g.:

const cdnUrl = store.getObjectUrl('foo/bar.jpg', 'https://mycdn.domian.com');
// cdnUrl should be `https://mycdn.domian.com/foo/bar.jpg`

.generateObjectUrl(name[, baseUrl])

Get the Object url. If provide baseUrl, will use baseUrl instead the default bucket and endpoint. Suggest use generateObjectUrl instead of getObjectUrl.

e.g.:

const url = store.generateObjectUrl('foo/bar.jpg');
// cdnUrl should be `https://${bucketname}.${endpotint}foo/bar.jpg`

const cdnUrl = store.generateObjectUrl('foo/bar.jpg', 'https://mycdn.domian.com');
// cdnUrl should be `https://mycdn.domian.com/foo/bar.jpg`

.head(name[, options])

Head an object and get the meta info.

parameters:

  • name {String} object name store on OSS
  • [options] {Object} optional parameters
    • [timeout] {Number} the operation timeout
    • [versionId] {String} the version id of history object
    • [headers] {Object} extra headers, detail see RFC 2616
      • 'If-Modified-Since' object modified after this time will return 200 and object meta, otherwise return 304 not modified
      • 'If-Unmodified-Since' object modified before this time will return 200 and object meta, otherwise throw PreconditionFailedError
      • 'If-Match' object etag equal this will return 200 and object meta, otherwise throw PreconditionFailedError
      • 'If-None-Match' object etag not equal this will return 200 and object meta, otherwise return 304 not modified

Success will return the object's meta information.

object:

  • status {Number} response status, maybe 200 or 304
  • meta {Object} object user meta, if not set on put(), will return null. If return status 304, meta will be null too
  • res {Object} response info, including
    • status {Number} response status
    • headers {Object} response headers
      • [x-oss-version-id] return in multiversion
    • size {Number} response size
    • rt {Number} request total use time (ms)

example:

  • Head an exists object and get user meta
await this.store.put('ossdemo/head-meta', Buffer.from('foo'), {
  meta: {
    uid: 1,
    path: 'foo/demo.txt'
  }
});
const object = await this.store.head('ossdemo/head-meta');
console.log(object);

// {
//   status: 200,
//   meta: {
//     uid: '1',
//     path: 'foo/demo.txt'
//   },
//   res: { ... }
// }
  • Head a not exists object
const object = await this.store.head('ossdemo/head-meta');
// will throw NoSuchKeyError

.getObjectMeta(name[, options])

Get an object meta info include ETag、Size、LastModified and so on, not return object content.

parameters:

  • name {String} object name store on OSS
  • [options] {Object} optional parameters
    • [timeout] {Number} the operation timeout
    • [versionId] {String} the version id of history object

Success will return the object's meta information.

object:

  • status {Number} response status
  • res {Object} response info, including
    • headers {Object} response headers

example:

  • Head an exists object and get object meta info
await this.store.put('ossdemo/object-meta', Buffer.from('foo'));
const object = await this.store.getObjectMeta('ossdemo/object-meta');
console.log(object);

// {
//   status: 200,
//   res: { ... }
// }

.get(name[, file, options])

Get an object from the bucket.

parameters:

  • name {String} object name store on OSS
  • [file] {String|WriteStream|Object} file path or WriteStream instance to store the content If file is null or ignore this parameter, function will return info contains content property. If file is Object, it will be treated as options.
  • [options] {Object} optional parameters
    • [versionId] {String} the version id of history object
    • [timeout] {Number} the operation timeout
    • [process] {String} image process params, will send with x-oss-process e.g.: {process: 'image/resize,w_200'}
    • [responseCacheControl] {String} default no-cache, (only support Browser). response-cache-control, will response with HTTP Header Cache-Control
    • [headers] {Object} extra headers, detail see RFC 2616
      • 'Range' get specifying range bytes content, e.g.: Range: bytes=0-9
      • 'If-Modified-Since' object modified after this time will return 200 and object meta, otherwise return 304 not modified
      • 'If-Unmodified-Since' object modified before this time will return 200 and object meta, otherwise throw PreconditionFailedError
      • 'If-Match' object etag equal this will return 200 and object meta, otherwise throw PreconditionFailedError
      • 'If-None-Match' object etag not equal this will return 200 and object meta, otherwise return 304 not modified

Success will return the info contains response.

object:

  • [content] {Buffer} file content buffer if file parameter is null or ignore
  • res {Object} response info, including
    • status {Number} response status
    • headers {Object} response headers
    • size {Number} response size
    • rt {Number} request total use time (ms)

If object not exists, will throw NoSuchKeyError.

example:

  • Get an exists object and store it to the local file
const filepath = '/home/ossdemo/demo.txt';
await store.get('ossdemo/demo.txt', filepath);

_ Store object to a writestream

await store.get('ossdemo/demo.txt', somestream);
  • Get an object content buffer
const result = await store.get('ossdemo/demo.txt');
console.log(Buffer.isBuffer(result.content));
  • Get a processed image and store it to the local file
const filepath = '/home/ossdemo/demo.png';
await store.get('ossdemo/demo.png', filepath, { process: 'image/resize,w_200' });
  • Get a not exists object
const filepath = '/home/ossdemo/demo.txt';
await store.get('ossdemo/not-exists-demo.txt', filepath);
// will throw NoSuchKeyError
  • Get a historic version object

`js const filepath = '/home/ossdemo/demo.

changelog

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

6.22.0 (2024-11-29)

Features

  • list object functions support return restore info (#1339) (986b743)
  • support restore Deep Cold Archive object (#1337) (ac500d3)
  • support PostObject policy V4 signature and restore archive object with setting of days (#1340) (ca8c027)

Bug Fixes

  • fix requestError return null and signatureUrlV4 run in Node 8.x (#1338) (439ffde)

6.21.0 (2024-08-16)

Features

  • bucket options support setting headers (#1306) (b4fb361)
  • callback supports callbackSNI (#1291) (fc6040b)
  • putBucketInventory supports new fields (#1290) (6bde1c2)
  • putBucketLifecycle supports ColdArchive and DeepColdArchive (#1256) (4c028d6)
  • support EC Code and get error detail from header (#1317) (5a95778)

Bug Fixes

  • multipartUpload supports setting storage-class header (#1308) (c29e15a)
  • add check to file of get (#1228) (c52bd5b)
  • fix the sorting of queries in signatureUrl (#1310) (b3cc7a0)
  • upgrade urllib to 2.44.0 (#1294)

6.20.0 (2024-01-19)

Features

6.19.0 (2023-12-18)

Features

  • verify object names strictly when signing URLs and enabled by default (#1265) (830e36e)

6.18.1 (2023-09-08)

Features

  • add default content-type in DingTalk for ios (#1244) (13a2691)

Bug Fixes

6.18.0 (2023-07-27)

Features

Bug Fixes

6.17.0 (2022-01-27)

Features

Bug Fixes

6.16.0 (2021-07-12)

Features

Bug Fixes

6.15.0 (2021-03-26)

Features

  • provide a switch to generate upload file md5 (#945) (2d65189)

6.14.1 (2021-03-23)

Bug Fixes

  • use arrayBuffer first, fall back to FileReader if it does not work (#943) (7c5fd52)

6.14.0 (2021-03-19)

Features

Bug Fixes

6.13.2 (2021-01-21)

Bug Fixes

  • not use object spread operator because of the low version of Node.js (#921) (cd50f88)

6.13.1 (2021-01-07)

Bug Fixes

6.13.0 (2021-01-06)

Features

Bug Fixes

  • node: deepCopy not working for large Buffers (#909) (f52cd2e)
  • do not copy buffer in completeMultipartUpload (#915) (c18f4ea)
  • merge conflict from master (860cf32)
  • should use encodeURIComponent insteadof encodeURI in copy api (#914) (9dceb70)
  • the continuation-token params in listV2 (#906) (df18401)
  • use lowercase header when calculating signatures (#910) (8e1adfd)

6.12.0 (2020-12-03)

Features

Bug Fixes

  • browser: checkpoint.file (#795) (4e38050)
  • browser test and listV2 docs (#901) (67f0e5f)
  • cannot use ali-oss in webworker (#823) (afb07f3)
  • check region and endpoint for ssrf (#874) (5457ecf)
  • getBucketVersions should use NextKeyMarker property (#896) (b9076d4)
  • host err which old image client request (#869) (b7b2f1c)
  • merge conflict #726 (#892) (6c77ecc)
  • use put insteadof putStream when calling multipartUpload to process small file in browser (#890) (cdd9995)

6.11.2 (2020-10-10)

Bug Fixes

  • browser: delete set header "User-Agent" (#873) (b11c162)

6.11.0 (2020-10-09)

Features

Bug Fixes

6.10.0 (2020-07-14)

Features

Bug Fixes

  • browser: put unhandle non-RequestTimeTooSkewed error (#825) (87dd7d6)
  • crypto each exports, close #473 (#830) (1cf7231)
  • WebFileReadStream no throw error when filereader onerror (#824) (d4977bf)

6.9.0 (2020-06-05)

Bug Fixes

Features

  • node: bucket policy (#751) (2d2b33a)
  • node: uploadPart support file stream (#798) (50321d4)
  • browser端,将 is-type-of 包的依赖处理为 shim (#801) (6f4ae51)
  • image processing (#744) (02d59da), closes #676
  • multiversion (#750) (9e8bb20)
  • putBucketWebsite support new parameter (#736) (e1cb438)
  • signatureUrl support trafficLimit (#756) (a57315f)
  • support for the latest putBucketLifecycle api features (#757) (17c2984)
  • update mime, use mime/lite replace mime and use shims/debug.js replace debug in browser (#802) (b4d1c56)

6.8.0 (2020-05-12)

Bug Fixes

  • browser: remove proto._statFile (#770) (fed2ba7 )
  • browser: remove sha256.js

Features

  • support multiversion api

6.7.0 (2020-04-17)

Bug Fixes

6.6.0 (2020-04-07)

Bug Fixes

Features

6.5.0 (2020-01-16)

Bug Fixes

  • bucket encryption test (#721) (a7d4904)
  • remove completeMultipartUpload encryption header (#718) (0ed0d57), closes #715
  • when value is Number,Buffer.alloc replace Buffer.from (#719) (4e137d4)

Features

6.4.0 (2019-12-19)

Features

  • browser: warnning when browser is not support (#703) (bd99280)
  • checkBucketName in setBucket/initOption/useBucket (#709) (162dfb5)
  • multipartupload support 'x-oss-server-side-encryption'
  • add bucket severside encryption

6.3.1 (2019-12-03)

Features

  • browser: copy for the browser (#697)

6.3.0 (2019-12-02)

Bug Fixes

5.3.0 (2018-06-20)

Bug Fixes

Features

5.1.1 (2018-04-16)

Bug Fixes

  • Browser: multipartUpload callback resumble parse error (#442) (e22ecf6)
  • Browser: signatureUrl with content-type and content-md5 (#441) (50f0093)

Features

5.1.0 (2018-04-14)

6.2.1 (2019-11-15)

Bug Fixes

6.2.0 (2019-11-13)

Bug Fixes

  • browser: set ascii_only to be true for browserify (#661) (e0ec299)
  • browser: support web work (#667) (655ee3d)
  • browser: put stream content empty when date is skew (#669) (48d9546)
  • node: bucket name cause ssrf attack (#666) (d200573)
  • node: putStream use third lib stream will signature error(#402) (c544bab)

Features

6.1.1 (2019-01-08)

Bug Fixes

  • support useFetch options to resovle browser compatibility
  • fix mulipartUpload bug in IE 10 or parallel == 1
  • fix invalid partSize

6.1.0 (2019-04-08)

Features

  • support requestPayer

Bug Fixes

  • repair codecov
  • docs

6.0.2 (2018-12-10)

Bug Fixes

6.0.1 (2018-07-17)

Bug Fixes

  • should consume the response stream on error (#503) (14e4038)

6.0.0 (2018-07-10)

Features

  • refactor async/await instead of generator and test case
  • remove region param about bucket operations
  • support cancel on node sdk
  • mount debug info on client proto
  • remove unuse browser.js in /

docs

  • README.md example

5.3.2 (2018-07-17)

Bug Fixes

  • should consume the response stream on error (#503) (14e4038)

5.3.1 (2018-06-27)

Bug Fixes

  • lock dependency stream-http 2.8.2

5.3.0 (2018-06-13)

Bug Fixes

Features

  • support getBucketLocation api in node sdk (#476) (2273a39)
  • support getBucketInfo api in node sdk (#476) (2273a39)

docs

5.2.0 (2018-05-08)

Bug Fixes

  • if browser support AbortController api , stream-http timeout err (#466) (69ad003)
  • rtml generate url (#463) (53f1f0c)
  • signatureUrl With response settings (#465) (3bf1be7)

Features

5.1.1 (2018-04-16)

Bug Fixes

  • Browser: multipartUpload callback resumble parse error (#442) (e22ecf6)
  • Browser: signatureUrl with content-type and content-md5 (#441) (50f0093)

Docs

5.1.0 (2018-04-14)

Features

5.0.1 (2018-04-10)

Bug Fixes

  • browser: use dist file for build tools (#430) (8494fbd)

  • sign method fix && ci support node 9 (f82bf8f3c)

Docs

  • add node and browser compatibility desc (f5de168e)

5.0.0 (2018-04-03)

Bug Fixes

Node >= 8 is required.

4.14.1 (2018-04-03)

Bug Fixes

4.14.0 (2018-03-30)

Bug Fixes

Features

4.13.2 (2018-03-13)

Bug Fixes

  • change timeout default value to 60s (fcb8847)

4.13.1 (2018-03-11)

Bug Fixes

  • fix bug about value of requestTimeout! (#383) (a3653a7)

4.13.0 (2018-03-07)

Bug Fixes

Features

fix

others

4.12.1 / 2018-01-29

features

fixs

others

4.11.5 / 2018-01-17

fixes

others

4.11.4 / 2018-01-09

fixes

others

4.11.3 / 2017-12-21

fixes

others

4.11.2 / 2017-11-07

fixes

4.11.1 / 2017-11-07

fixes

4.11.0 / 2017-10-25

features

4.10.2 / 2017-10-20

fixes

others

4.10.1 / 2017-08-30

  • fix issue #288: startsWith not support by ie11 (#289)
  • fix: add 4.10.0 dist

4.10.0 / 2017-08-07

features

fixes

4.9.0 / 2017-07-28

  • feat: support oss.append (#275)
  • test: add node 8
  • test: skip callbackurl test cases
  • test: set default platform on user-agent
  • docs: Document secure option when creating bucket store. (#252)
  • chore: add dist build files

4.8.0 / 2017-01-19

  • feat: support VPC region #181 (#183)
  • fix comment typo and add object check to avoid call properties of null object (#176)

4.7.3 / 2017-01-06

  • update dist

4.7.2 / 2017-01-06

  • update dist

4.7.1 / 2017-01-06

  • :bug: fix bowser dependency (#174)

4.7.0 / 2017-01-05

  • fix: the copy object api bug which can not use non-English source object name (#166)
  • feat: add process params to signatureUrl and get api for image process (#170)
  • fix: multipartUpload can not work with IE10 bug (#167)

4.6.3 / 2016-12-20

  • fix request stream bug of the multipart upload feature (#155)
  • chore(package): update dateformat to version 2.0.0 (#156)
  • doc: param "file" of *get method is optional (#158)

4.6.2 / 2016-10-28

  • Fix browserify transform with co-gather (#150)

4.6.0 / 2016-10-27

  • feat: implement parallel uploading for multipartUpload (#149)

4.5.0 / 2016-10-13

  • feat: add options.ctx for every request params (#144)
  • chore(package): update urllib to version 2.16.1 (#146)
  • chore(package): update uglify-js to version 2.7.1
  • chore(package): update should to version 11.0.0
  • chore(package): update mocha to version 3.0.0
  • chore(package): update mm to version 2.0.0
  • chore(package): update mm to version 1.5.1
  • chore(package): update should to version 10.0.0 (#125)
  • doc: Update API doc for .multipartUpload
  • chore(package): update should to version 9.0.2

4.4.4 / 2016-06-04

  • deps: use ^
  • Fix isGeneratorFunction and Date format problems in IE10 (#118)
  • chore(package): update humanize-ms to version 1.2.0

4.4.3 / 2016-05-17

  • fix: memory leak in multipart (#113) (#114)
  • chore(package): update utility to version 1.8.0
  • chore(package): update urllib to version 2.9.1 (#111)

4.4.2 / 2016-05-05

  • fix: support node 6 (#109)

4.4.1 / 2016-05-04

  • fix: Correctly parse Put/MultipartUpload response when using upload callback (#104)
  • chore(package): update babel-plugin-transform-runtime to version 6.8.0 (#103)

4.4.0 / 2016-04-28

  • add options.ignoreStatusFile to ignore put status file for status check (#100)

4.3.0 / 2016-04-14

  • deps: uglify-js
  • Add a wrapper to return Promise (#95)

4.2.2 / 2016-04-12

  • Rework browser build to reduce dist size (#94)
  • chore(package): update babel-plugin-transform-runtime to version 6.7.5
  • test: add update exists object headers test case

4.2.1 / 2016-04-07

  • fix: add getObjectUrl on cluster client

4.2.0 / 2016-04-07

  • feat: introduce getObjectUrl method

4.1.7 / 2016-03-30

  • Trim access key id/secret

4.1.6 / 2016-03-16

  • Replace babel-polyfill with babel-runtime to avoid conflict with react
  • chore(package): update sdk-base to version 2.0.1
  • chore(package): update sdk-base to version 2.0.0

4.1.5 / 2016-03-02

  • add README for multipart
  • provide checkpoint in multipart upload progress
  • allow more HTTP methods in signatureUrl
  • allow config expires in signatureUrl
  • ignore image-client coverage
  • stop check leaks in test, work around #74
  • chore(package): update urllib to version 2.8.0
  • fix post-release

4.1.4 / 2016-01-28

  • improve user-agent test
  • use platform to detect browser user agent
  • add script to publish dist/ to cdn after each release

4.1.3 / 2016-01-27

  • chore: update README
  • add user-agent in header

4.1.2 / 2016-01-27

  • update dist

4.1.1 / 2016-01-27

  • deps: update dependencies
  • update dist
  • add build-dist script

4.1.0 / 2016-01-26

  • refine put/putStream interfaces
  • add putACL & getACL
  • fix bug when endpoint is IP with port

4.0.1 / 2016-01-25

  • fix IE10 compatibility and refine test

4.0.0 / 2016-01-22

  • build: only test on 4&5
  • Merge pull request #55 from rockuw/master
  • add .babelrc
  • use readAsArrayBuffer for IE11 doesn't support readAsBinaryString
  • reduce putBucketACL() case
  • avoid putBucketACL() timeout
  • sleep logger in bucket.test.js
  • add node 5 and tidy .travis.yml
  • use ms to tidy code
  • Wait some time in test for bucket meta sync
  • make region configurable
  • test travis ci
  • Set sts client default timeout to 60s
  • test travis ci
  • handle policy string in STS
  • Merge pull request #57 from ali-sdk/greenkeeper-autod-2.4.2
  • fix cdn addr
  • use utility.escape
  • chore(package): update autod to version 2.4.2
  • refine as review comments
  • add object key encoding test
  • refine bucket test
  • add content type test
  • add browser usage in README
  • signatureUrl() supports STS
  • refine as review comments
  • Merge pull request #56 from ali-sdk/greenkeeper-merge-descriptors-1.0.1
  • chore(package): update merge-descriptors to version 1.0.1
  • add policy to STS assumeRole
  • correct author & cont. remove indent tabs
  • expose .putData as public function
  • remove indent tabs
  • add comments to browser.js
  • add browser.js and change 'let' to 'var'
  • move multipart into a separate file
  • refine subres
  • rich multipart test
  • support STS in oss client
  • add STS client, test pass
  • fix bug in uploadPart, and refine multipart test
  • support generator progress callback
  • add progress callback
  • browser multipartUpload test pass
  • multipart for server test pass
  • fix object url
  • pass all tests
  • refine client constructor to handle endpoint/ip/cname/region
  • Change 'Date' header to 'x-oss-date' for browser compatibility

3.1.3 / 2015-12-18

  • fix(object): custom content-type support lower case
  • deps: update dependencies

3.1.2 / 2015-10-26

  • feat: support custom Content-Type

3.1.1 / 2015-10-23

  • fix(cluster): simplify cluster config

3.1.0 / 2015-10-23

  • feat: support custom urllib client
  • chore: add node required on package.json

3.0.3 / 2015-10-03

  • feat: change check status file path

3.0.2 / 2015-10-01

  • feat: make chooseAvailable public

3.0.1 / 2015-09-30

3.0.0 / 2015-09-30

  • refactor: change signatureUrl to normal function
  • feat: add available checking

2.8.0 / 2015-09-29

  • test: cluster store to two different bucket
  • feat: support signatureUrl
  • feat: add clusterClient

2.7.0 / 2015-09-22

  • feat: support cname and object url

2.6.1 / 2015-09-09

  • add endpoint into readme
  • chore: fix codecov link

2.6.0 / 2015-09-07

  • test: skip image upload
  • docs: add putStream doc
  • test: use codecov
  • feat: put object support streaming

2.5.1 / 2015-08-24

  • fix: remove unnecessary decode
  • fix: signature url
  • fix: escape resource

2.5.0 / 2015-08-22

  • chore: travis use sudo: false
  • feat: request error add params info

2.4.0 / 2015-08-15

  • feat(createRequest): expose create request method
  • deps upgrade

2.3.0 / 2015-07-25

  • feature: support custom agent by options.agent

2.2.0 / 2015-04-02

  • Image service API (@zensh)

2.1.0 / 2015-03-23

  • feat: add getStream*() api

2.0.0 / 2015-02-28

  • fix get not exists object TypeError
  • transfer to ali-sdk/ali-oss
  • feat(object): support streaming put
  • refactor object operations with successStatuses and xmpResponse
  • finish bucket operations
  • ensure tmp dir exists
  • add appveyor.yml
  • add bucket operations
  • support deleteMulti
  • support copy and updateMeta
  • support get object
  • support delete object
  • totally refactor according to ali-sdk

1.1.0 / 2015-01-30

  • feat: support signature url

1.0.0 / 2014-10-26

  • use urllib replace of co-urllib
  • fix readme
  • ocd
  • update examples

0.0.3 / 2014-04-11

  • update co-urllib, add mime, add alias

0.0.2 / 2014-04-10

  • fix 404 error handler
  • Merge branch 'master' of github.com:node-modules/ali-oss
  • add istanbul
  • Merge pull request #1 from chunpu/patch-1
  • fix regenerator url

0.0.1 / 2014-04-08

  • fix readme
  • add travis-ci
  • use renegerator
  • update readme
  • add callback example
  • add test
  • finish get and remove
  • complete upload
  • Initial commit