oss-client
Alibaba cloud OSS(Object Storage Service) Node.js Client.
Install
npm install oss-client
License
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
- oss-client
- OSS Usage
- Summary
- Node.js Usage
- Data Regions
- Create Account
- Create A Bucket Instance
- new OSSObject(options)
- Object Operations
- .put(name, file[, options])
- .putStream(name, stream[, options])
- .append(name, file[, options])
- .generateObjectUrl(name[, baseUrl])
- .head(name[, options])
- .getObjectMeta(name[, options])
- .get(name[, file, options])
- .getStream(name[, options])
- .delete(name[, options])
- .copy(name, sourceName[, sourceBucket, options])
- .putMeta(name, meta[, options])
- .deleteMulti(names[, options])
- .list(query[, options])
- .listV2(query[, options])
- .getBucketVersions(query[, options])
- .signatureUrl(name[, options])
- .asyncSignatureUrl(name[, options])
- .putACL(name, acl[, options])
- .getACL(name[, options])
- .restore(name[, options])
- .putSymlink(name, targetName[, options])
- .getSymlink(name[, options])
- .calculatePostSignature(policy)
- .getObjectTagging(name[, options])
- .putObjectTagging(name, tag[, options])
- .deleteObjectTagging(name[, options])
- .processObjectSave(sourceObject, targetObject, process[, targetBucket])
- Known Errors
- Contributors
Node.js Usage
Compatibility
- Node.js >= 16.0.0
- urllib >= 3.0.0
Basic usage
- install SDK using npm
npm install oss-client
- for example:
Commonjs
const { OSSObject } = require('oss-client');
const ossObject = new OSSObject({
region: '<oss region>',
endpoint: '<oss endpoint>',
accessKeyId: '<Your accessKeyId>',
accessKeySecret: '<Your accessKeySecret>',
bucket: '<Your bucket name>',
});
TypeScript and ESM
import { OSSObject } from 'oss-client';
const ossObject = new OSSObject({
region: '<oss region>',
endpoint: '<oss endpoint>',
accessKeyId: '<Your accessKeyId>',
accessKeySecret: '<Your accessKeySecret>',
bucket: '<Your bucket name>',
});
Data Regions
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
.
new OSSObject(options)
Create a Bucket store instance.
options:
- accessKeyId {String} access key you create on aliyun console website
- accessKeySecret {String} access secret you create
- [bucket] {String} the default bucket you want to access
- [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 settrue
to save lot of money. - [timeout] {String|Number} instance level timeout for all operations, default is
60s
. - [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
example:
- basic usage
const { OSSObject } = require('oss-client');
const store = new OSSObject({
accessKeyId: 'your access key',
accessKeySecret: 'your access secret',
bucket: 'your bucket name',
region: 'oss-cn-hangzhou',
});
- use accelerate endpoint
- Global accelerate endpoint: oss-accelerate.aliyuncs.com
- Accelerate endpoint of regions outside mainland China: oss-accelerate-overseas.aliyuncs.com
const { OSSObject } = require('oss-client');
const store = new OSSObject({
accessKeyId: 'your access key',
accessKeySecret: 'your access secret',
bucket: 'your bucket name',
endpoint: 'https://oss-accelerate.aliyuncs.com',
});
- use custom domain
See https://help.aliyun.com/zh/oss/user-guide/map-custom-domain-names-5
const { OSSObject } = require('oss-client');
const store = new OSSObject({
accessKeyId: 'your access key',
accessKeySecret: 'your access secret',
cname: true,
// your custom domain endpoint
endpoint: 'https://my-static.domain.com',
});
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} object local path, content buffer or ReadStream content instance use in Node, Blob and html5 File
[options] {Object} optional parameters
[timeout] {Number} the operation timeout
[mime] {String} custom mime, will send with
Content-Type
entity header[meta] {Object} user meta, will send with
x-oss-meta-
prefix string e.g.:{ uid: 123, pid: 110 }
[callback] {Object} The callback parameter is composed of a JSON string encoded in Base64,detail see
url {String} After a file is uploaded successfully, the OSS sends a callback request to this URL.
[host] {String} The host header value for initiating callback requests.
body {String} The value of the request body when a callback is initiated, for example,
key=${key}&etag=${etag}&my_var=${x:my_var}
.[contentType] {String} The Content-Type of the callback requests initiatiated, It supports application/x-www-form-urlencoded and application/json, and the former is the default value.
[customValue] {Object} Custom parameters are a map of key-values
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
- 'Cache-Control' cache control for download, e.g.:
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.
[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
- 'Cache-Control' cache control for download, e.g.:
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
- 'Cache-Control' cache control for download, e.g.:
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
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,
});
.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} file path or WriteStream instance to store the content
If
file
is null or ignore this parameter, function will return info containscontent
property. - [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'}
- [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
- 'Range' get specifying range bytes content, e.g.:
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
const filepath = '/home/ossdemo/demo.txt';
const versionId = 'versionId string';
await store.get('ossdemo/not-exists-demo.txt', filepath, {
versionId,
});
.getStream(name[, options])
Get an object read stream.
parameters:
- name {String} object name store on OSS
- [options] {Object} optional parameters
- [timeout] {Number} the operation timeout
- [process] {String} image process params, will send with
x-oss-process
- [headers] {Object} extra headers
- '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 stream instance and response info.
object:
- stream {ReadStream} readable stream instance
if response status is not 200, stream will be
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)
If object not exists, will throw NoSuchKeyError.
example:
- Get an exists object stream
const result = await store.getStream('ossdemo/demo.txt');
result.stream.pipe(fs.createWriteStream('some file.txt'));
.delete(name[, options])
Delete an object from the bucket.
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 info contains response.
object:
- 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 delete object not exists, will also delete success.
example:
- Delete an exists object
await store.delete('ossdemo/someobject');
- Delete a not exists object
await store.delete('ossdemo/some-not-exists-object');
- Delete a history object or deleteMarker
const versionId = 'versionId';
await store.delete('ossdemo/some-not-exists-object', { versionId });
.copy(name, sourceName[, sourceBucket, options])
Copy an object from sourceName
to name
.
parameters:
- name {String} object name store on OSS
- sourceName {String} source object name
- [sourceBucket] {String} source Bucket. if doesn't exist,
sourceBucket
is same bucket. - [options] {Object} optional parameters
- [versionId] {String} the version id of history object
- [timeout] {Number} the operation timeout
- [meta] {Object} user meta, will send with
x-oss-meta-
prefix string e.g.:{ uid: 123, pid: 110 }
If themeta
set, will override the source object meta. - [headers] {Object} extra headers
- 'If-Match' do copy if source object etag equal this, otherwise throw PreconditionFailedError
- 'If-None-Match' do copy if source object etag not equal this, otherwise throw PreconditionFailedError
- 'If-Modified-Since' do copy if source object modified after this time, otherwise throw PreconditionFailedError
- 'If-Unmodified-Since' do copy if source object modified before this time, otherwise throw PreconditionFailedError
- See more: CopyObject
Success will return the copy result in data
property.
object:
- data {Object} copy result
- lastModified {String} object last modified GMT string
- etag {String} object etag contains
"
, e.g.:"5B3C1A2E053D763E1B002CC607C5A0FE"
- 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 source object not exists, will throw NoSuchKeyError.
example:
- Copy same bucket object
store.copy('newName', 'oldName').then(result => {
console.log(result);
});
- Copy other bucket object
store.copy('logo.png', 'logo.png', 'other-bucket').then(result => {
console.log(result);
});
- Copy historic object
const versionId = 'your verisonId';
store
.copy('logo.png', 'logo.png', 'other-bucket', { versionId })
.then(result => {
console.log(result);
});
.putMeta(name, meta[, options])
Set an exists object meta.
parameters:
- name {String} object name store on OSS
- meta {Object} user meta, will send with
x-oss-meta-
prefix string e.g.:{ uid: 123, pid: 110 }
Ifmeta: null
, will clean up the exists meta - [options] {Object} optional parameters
- [timeout] {Number} the operation timeout
Success will return the putMeta result in data
property.
- data {Object} copy result
- lastModified {String} object last modified GMT date, e.g.:
2015-02-19T08:39:44.000Z
- etag {String} object etag contains
"
, e.g.:"5B3C1A2E053D763E1B002CC607C5A0FE"
- lastModified {String} object last modified GMT date, e.g.:
- 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:
- Update exists object meta
const result = await store.putMeta('ossdemo.txt', {
uid: 1,
pid: 'p123',
});
console.log(result);
- Clean up object meta
await store.putMeta('ossdemo.txt', null);
.deleteMulti(names[, options])
Delete multi objects in one request.
parameters:
- names {Array