$ npm install 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
npm install ali-oss --save
Node.js >= 8.0.0 required. You can use 4.x in Node.js < 8.
Note
:
You can join DingDing Talk Group, Group Link
OSS, Object Storage Service. Equal to well known Amazon S3.
All operation use es7 async/await to implement. All api is async function.
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>'
});
You can use most of the functionalities of ali-oss
in browser with
some exceptions:
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.
As browser-side javascript involves CORS operations. You need to setup your bucket CORS rules to allow CORS operations:
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.
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].
npm run build-dist
And see the build artifacts under dist/
.
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 |
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
.
Each OSS instance required accessKeyId
, accessKeySecret
and bucket
.
Create a Bucket store instance.
options:
stsToken
、accessKeyId
、accessKeySecret
when sts info expires. return value must be object contains stsToken
、accessKeyId
、accessKeySecret
putBucket()
create one first.region
. Set as extranet domain name, intranet domain name, accelerated domain name, etc. according to different needs. please see endpointsoss-cn-hangzhou
.false
.
If your servers are running on aliyun too, you can set true
to save a lot of money.60s
.endpoint
field with your custom domain name,'x-oss-request-payer': 'requester'
to oss server.
the details you can see requestPayfetch
mode ,else XMLHttpRequest
put
with stream, putStream
, append
with stream because the stream can only be consumed onceexample:
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'
});
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'
});
const OSS = require('ali-oss');
const store = new OSS({
accessKeyId: 'your access key',
accessKeySecret: 'your access secret',
cname: true,
endpoint: 'your custome domain'
});
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
});
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);
}
}
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);
}
List buckets in this account.
parameters:
null
prefix
keymarker
, including marker
key100
, limit to 1000
Success will return buckets list on buckets
properties.
BucketMeta
will contains blow properties:
oss-cn-hangzhou-a
2015-02-19T08:39:44.000Z
Standard
, IA
, Archive
id
and displayName
example:
store
.listBuckets({
'max-keys': 10
})
.then(result => {
console.log(result);
});
Create a new bucket.
parameters:
private
,public-read
,public-read-write
LRS
, include LRS
,ZRS
Success will return the bucket name on bucket
properties.
example:
helloworld
location on HongKongstore.putBucket('helloworld').then(result => {
// use it by default
store.useBucket('helloworld');
});
helloworld
location on HongKong StorageClass Archive
await store.putBucket('helloworld', { StorageClass: 'Archive' });
// use it by default
store.useBucket('helloworld');
Delete an empty bucket.
parameters:
Success will return:
example:
store.deleteBucket('helloworld').then(result => {});
Use the bucket.
parameters:
example:
helloworld
as the default bucketstore.useBucket('helloworld');
Get bucket information,include CreationDate、ExtranetEndpoint、IntranetEndpoint、Location、Name、StorageClass、 Owner、AccessControlList、Versioning
parameters:
example:
helloworld
as the default bucketstore.getBucketInfo('helloworld').then(res => {
console.log(res.bucket);
});
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:
Success will return:
stat {Object} container for the BucketStat structure:
res {Object} response info, including
example:
store.getBucketStat().then(res => console.log(res));
Get bucket location
parameters:
example:
helloworld
as the default bucketstore.getBucketLocation('helloworld').then(res => {
console.log(res.location);
});
Update the bucket ACL.
parameters:
public-read-write
, public-read
and private
Success will return:
example:
helloworld
to public-read-write
store.putBucketACL('helloworld', 'public-read-write').then(result => {});
Get the bucket ACL.
parameters:
Success will return:
example:
helloworld
store.getBucketACL('helloworld').then(result => {
console.log(result.acl);
});
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:
Success will return:
example:
helloworld
logging and save with prefix logs/
store.putBucketLogging('helloworld', 'logs/').then(result => {});
Get the bucket logging settings.
parameters:
Success will return:
null
example:
helloworld
logging settingsstore.getBucketLogging('helloworld').then(result => {
console.log(result.enable, result.prefix);
});
Delete the bucket logging settings.
parameters:
Success will return:
Set the bucket as a static website.
parameters:
index.html
Success will return:
example:
store
.putBucketWebsite('hello', {
index: 'index.html'
})
.then(result => {});
Get the bucket website config.
parameters:
Success will return:
null
Delete the bucket website config.
parameters:
Success will return:
Set the bucket request Referer
white list.
parameters:
Referer
white list, e.g.:['https://npm.taobao.org', 'http://cnpmjs.org'];
Success will return:
example:
store.putBucketReferer('hello', false, ['https://npm.taobao.org', 'http://cnpmjs.org']).then(result => {});
Get the bucket request Referer
white list.
parameters:
Success will return:
Referer
white listDelete the bucket request Referer
white list.
parameters:
Success will return:
Set the bucket object lifecycle.
parameters:
Rule
will contains blow properties:
Enabled
or Disabled
days
2022-10-11T00:00:00.000Z
true
createdBeforeDate
and days
and expiredObjectDeleteMarker
must have one.days
2022-10-11T00:00:00.000Z
createdBeforeDate
and days
must have one.IA
or Archive
or ColdArchive
or DeepColdArchive
days
2022-10-11T00:00:00.000Z
createdBeforeDate
and days
must have one.IA
or Archive
or ColdArchive
or DeepColdArchive
noncurrentDays
expiration
、 abortMultipartUpload
、 transition
、 noncurrentVersionTransition
must have one.noncurrentDays
tag
cannot be used with abortMultipartUpload
Success will return:
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);
Get the bucket object lifecycle.
parameters:
Success will return:
Delete the bucket object lifecycle.
parameters:
Success will return:
Set CORS rules of the bucket object
parameters:
Rule
will contains below properties:
Success will return:
example:
store
.putBucketCORS('hello', [
{
allowedOrigin: '*',
allowedMethod: ['GET', 'HEAD']
}
])
.then(result => {});
Get CORS rules of the bucket object.
parameters:
Success will return:
Delete CORS rules of the bucket object.
parameters:
Success will return:
get RequestPayment value of the bucket object.
parameters:
Success will return:
put RequestPayment value of the bucket object.
parameters:
Success will return:
put BucketEncryption value of the bucket object.
parameters:
Success will return:
get BucketEncryption rule value of the bucket object.
parameters:
Success will return:
delete BucketEncryption rule value of the bucket object.
parameters:
Success will return:
Adds tags for a bucket or modify the tags for a bucket.
parameters:
{var1: value1,var2:value2}
Success will return:
Obtains the tags for a bucket.
parameters:
Success will return:
Deletes the tags added for a bucket.
parameters:
Success will return:
Adds or modify policy for a bucket.
parameters:
Success will return:
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);
Obtains the policy for a bucket.
parameters:
Success will return:
Deletes the policy added for a bucket.
parameters:
Success will return:
Obtains the version status of an object
parameters:
Success will return:
Suspended
or Enabled
. default value: undefined
set the version status of an object
parameters:
Enabled
or Suspended
Success will return:
get bucket inventory by inventory-id
parameters:
Success will return:
async function getBucketInventoryById() {
try {
const result = await store.getBucketInventory('bucket', 'inventoryid');
console.log(result.inventory);
} catch (err) {
console.log(err);
}
}
getBucketInventoryById();
set bucket inventory
parameters:
Success will return:
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();
delete bucket inventory by inventory-id
parameters:
Success will return:
list bucket inventory
parameters:
Success will return:
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();
used to delete an unlocked retention policy.
parameters:
Success will return:
used to lock a retention policy.
parameters:
Success will return:
used to extend the retention period of objects in a bucket whose retention policy is locked.
parameters:
Success will return:
used to query the retention policy information of the specified bucket.
parameters:
Success will return:
Locked
or InProgress
create a retention policy.
parameters:
Success will return:
All operations function return Promise, except signatureUrl
.
Add an object to the bucket.
parameters:
Content-Type
entity headerx-oss-meta-
prefix string
e.g.: { uid: 123, pid: 110 }
key=${key}&etag=${etag}&my_var=${x:my_var}
.var customValue = { var1: 'value1', var2: 'value2' };
Cache-Control: public, no-cache
Content-Disposition: somename
Content-Encoding: gzip
Tue, 08 Dec 2020 13:49:43 GMT
Success will return the object information.
object:
example:
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
// }
// }
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
// }
// }
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
// }
// }
Add a stream object to the bucket.
parameters:
chunked encoding
will be used if absentContent-Type
entity headerx-oss-meta-
prefix string
e.g.: { uid: 123, pid: 110 }
var customValue = { var1: 'value1', var2: 'value2' };
Cache-Control: public, no-cache
Content-Disposition: somename
Content-Encoding: gzip
Tue, 08 Dec 2020 13:49:43 GMT
Success will return the object information.
object:
example:
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 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
Content-Type
entity headerx-oss-meta-
prefix string
e.g.: { uid: 123, pid: 110 }
Cache-Control: public, no-cache
Content-Disposition: somename
Content-Encoding: gzip
Tue, 08 Dec 2020 13:49:43 GMT
object:
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
});
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`
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 an object and get the meta info.
parameters:
Success will return the object's meta information.
object:
put()
, will return null.
If return status 304, meta will be null tooexample:
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: { ... }
// }
const object = await this.store.head('ossdemo/head-meta');
// will throw NoSuchKeyError
Get an object meta info include ETag、Size、LastModified and so on, not return object content.
parameters:
Success will return the object's meta information.
object:
example:
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 an object from the bucket.
parameters:
file
is null or ignore this parameter, function will return info contains content
property.
If file
is Object, it will be treated as options.x-oss-process
e.g.: {process: 'image/resize,w_200'}
no-cache
, (only support Browser). response-cache-control, will response with HTTP Header Cache-Control
Range: bytes=0-9
Success will return the info contains response.
object:
file
parameter is null or ignoreIf object not exists, will throw NoSuchKeyError.
example:
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);
const result = await store.get('ossdemo/demo.txt');
console.log(Buffer.isBuffer(result.content));
const filepath = '/home/ossdemo/demo.png';
await store.get('ossdemo/demo.png', filepath, { process: 'image/resize,w_200' });
const filepath = '/home/ossdemo/demo.txt';
await store.get('ossdemo/not-exists-demo.txt', filepath);
// will throw NoSuchKeyError
const filepath = '/home/ossdemo/demo.txt';
const versionId = 'versionId string';
aw
© 2010 - cnpmjs.org x YWFE | Home | YWFE