### Full BceBaseClient Usage Example
Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/BceBaseClient.md
Demonstrates creating a BceBaseClient instance, listening for events, and sending a GET request. Ensure you replace placeholder credentials.
```javascript
const {BceBaseClient} = require('@baiducloud/sdk');
// 创建基础客户端实例
const client = new BceBaseClient({
credentials: {
ak: 'your-access-key',
sk: 'your-secret-key'
},
region: 'bj',
protocol: 'https'
}, 'bos', true); // 'bos' 支持多区域
// 监听事件
client.on('progress', (event) => {
console.log(`Progress: ${event.loaded}/${event.total}`);
});
client.on('error', (error) => {
console.error('Request error:', error.message);
});
// 发送请求
client.sendRequest('GET', '/my-bucket', {
headers: {'Host': client.config.endpoint.replace('https://', '')},
params: {maxKeys: 100},
config: {
protocol: 'https',
region: 'bj'
}
})
.then(response => {
console.log('Response headers:', response.http_headers);
console.log('Response body:', response.body);
})
.catch(error => {
console.error('Error:', error);
});
```
--------------------------------
### Browser Environment Usage Example
Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/01-简介与项目概览.md
Example of initializing the BosClient in a browser environment using the CDN-included SDK. Replace placeholders with your actual credentials and endpoint.
```html
```
--------------------------------
### Install SDK via NPM
Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/01-简介与项目概览.md
Use npm to install the Baidu Cloud Engine JavaScript SDK.
```bash
npm install @baiducloud/sdk
```
--------------------------------
### BosClient Basic Operations Example
Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/BosClient-基础操作.md
Demonstrates a complete workflow of basic BosClient operations: listing buckets, uploading a file from local disk, retrieving file metadata, downloading the file, and deleting the file. Ensure you have the necessary credentials and a bucket named 'my-bucket' with a local file './backup.zip' for this example to run.
```javascript
const {BosClient} = require('@baiducloud/sdk');
const fs = require('fs');
const client = new BosClient({
credentials: {
ak: process.env.BAIDU_AK,
sk: process.env.BAIDU_SK
},
region: 'bj'
});
async function demo() {
try {
// 列出所有 bucket
const listRes = await client.listBuckets();
console.log('Available buckets:', listRes.body.buckets.map(b => b.name));
// 上传文件
await client.putObjectFromFile('my-bucket', 'backup.zip', './backup.zip', {
'x-bce-storage-class': 'STANDARD'
});
console.log('File uploaded');
// 获取文件元数据
const metaRes = await client.getObjectMetadata('my-bucket', 'backup.zip');
console.log('File size:', metaRes.http_headers['content-length']);
// 下载文件
await client.getObjectToFile('my-bucket', 'backup.zip', './restore.zip');
console.log('File downloaded');
// 删除文件
await client.deleteObject('my-bucket', 'backup.zip');
console.log('File deleted');
} catch (error) {
console.error('Error:', error.message);
}
}
demo();
```
--------------------------------
### Install BCE-SDK-JS via npm
Source: https://github.com/baidubce/bce-sdk-js/blob/master/docs/setup.md
Install the JavaScript SDK development package using npm for Node.js environments.
```bash
npm install @baiducloud/sdk
```
--------------------------------
### Node.js Environment Usage Example
Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/01-简介与项目概览.md
Example of initializing and using the BosClient in a Node.js environment to list buckets. Ensure you replace placeholders with your actual credentials and endpoint.
```javascript
const {BosClient} = require('@baiducloud/sdk');
const client = new BosClient({
credentials: {
ak: 'your-access-key',
sk: 'your-secret-key'
},
endpoint: 'https://bj.bcebos.com',
region: 'bj'
});
// 列出所有 bucket
client.listBuckets().then(response => {
console.log(response.body.buckets);
}).catch(error => {
console.error(error);
});
```
--------------------------------
### Browser Environment Example: Upload Object from String
Source: https://github.com/baidubce/bce-sdk-js/blob/master/docs/setup.md
Example using the BosClient in a browser environment to upload an object from a string after including the SDK.
```javascript
```
--------------------------------
### Node.js Example: Upload Object from File
Source: https://github.com/baidubce/bce-sdk-js/blob/master/docs/setup.md
Example using ES6 syntax to upload an object from a file using the BosClient in a Node.js environment. Requires Babel support for older Node.js versions.
```javascript
import {BosClient} from '@baiducloud/sdk';
const config = {
endpoint: , //传入Bucket所在区域域名
credentials: {
ak: , //您的AccessKey
sk: //您的SecretAccessKey
}
};
let bucket = 'my-bucket';
let key = 'hello.js';
let client = new BosClient(config);
client.putObjectFromFile(bucket, key, __filename)
.then(response => console.log(response)) // 成功
.catch(error => console.error(error)); // 失败
```
--------------------------------
### Initialize Baidu Cloud App
Source: https://github.com/baidubce/bce-sdk-js/blob/master/test/browser/demo/index.html
Starts the Baidu Cloud application after the ESL configuration is complete. This is the main entry point for the SDK's functionality.
```javascript
esl(['app'], function (app) {
app.start();
});
```
--------------------------------
### BosClient Event Listeners for Uploads
Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/BosClient-基础操作.md
Sets up event listeners for upload progress, errors, aborts, and timeouts when using BosClient. This example demonstrates how to monitor the upload status of a file.
```javascript
const client = new BosClient({...});
// 监听上传进度
client.on('progress', (event) => {
console.log(`Progress: ${event.loaded} / ${event.total}`);
console.log(`Percentage: ${Math.floor(event.loaded / event.total * 100)}%`);
});
// 监听错误
client.on('error', (error) => {
console.error('Error occurred:', error.message);
});
// 监听中止
client.on('abort', () => {
console.log('Request was aborted');
});
// 监听超时
client.on('timeout', () => {
console.log('Request timeout');
});
client.putObject('my-bucket', 'large-file.bin', fileStream)
.then(() => console.log('Upload completed'))
.catch(error => console.error(error));
```
--------------------------------
### Event Listener for Upload Progress
Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/01-简介与项目概览.md
Example of attaching an event listener to a client to monitor upload progress. The 'progress' event provides loaded and total bytes.
```javascript
client.on('progress', (event) => {
console.log(`已上传 ${event.loaded} / ${event.total}`);
});
```
--------------------------------
### Async/Await Error Handling with Specific Codes
Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/errors.md
Shows how to handle errors in an async function using a try...catch block. This example specifically checks for 'NoSuchKey' and 'AccessDenied' errors, logging user-friendly messages, and re-throws any other unexpected errors.
```javascript
async function safeDownload(bucket, key) {
try {
const response = await client.getObject(bucket, key);
return response.body;
} catch (error) {
if (error['x-bce-code'] === 'NoSuchKey') {
console.log('Object does not exist');
return null;
} else if (error['x-bce-code'] === 'AccessDenied') {
console.log('Permission denied');
return null;
} else {
throw error;
}
}
}
```
--------------------------------
### Generate Basic Authorization Header
Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/Auth.md
Calculate a BCE V1 signature for a GET request with query parameters and custom headers. The SDK typically handles this automatically.
```javascript
const {Auth} = require('@baiducloud/sdk');
const auth = new Auth('ak', 'sk');
// 基础签名
const sig1 = auth.generateAuthorization(
'GET',
'/my-bucket/my-object',
{versionId: '123'},
{'Host': 'bj.bcebos.com', 'Content-Type': 'text/plain'}
);
console.log('Authorization:', sig1);
```
--------------------------------
### Configure ESL for Baidu Cloud SDK
Source: https://github.com/baidubce/bce-sdk-js/blob/master/test/browser/demo/index.html
Configures the Enhanced Script Loader (ESL) to load the Baidu Cloud SDK and its dependencies. This setup is particularly useful in environments like Electron where 'require' might be overridden.
```javascript
esl.config({
waitSeconds: 10,
baseUrl: 'src',
packages: [
{
name: 'baidubce-sdk',
location: '../dep/baidubce-sdk/0.0.0',
main: 'baidubce-sdk.bundle'
},
{
name: 'jquery',
location: '../dep/jquery/0.0.0',
main: 'jquery'
},
{
name: 'async',
location: '../dep/async/0.0.0',
main: 'async'
},
{
name: 'etpl',
location: '../dep/etpl/3.0.0/src',
main: 'main'
},
{
name: 'humanize',
location: '../dep/humanize/0.0.9/src',
main: 'main'
},
{
name: 'moment',
location: '../dep/moment/2.7.0/src',
main: 'moment'
},
{
name: 'underscore',
location: '../dep/underscore/1.6.0/src',
main: 'underscore'
},
{
name: 'msr',
location: '../dep/msr/0.0.0/src',
main: 'MediaStreamRecorder'
},
{
name: 'store',
location: '../dep/store/1.3.9/src',
main: 'store'
}
]
});
```
--------------------------------
### List Buckets
Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/BosClient-基础操作.md
Retrieves a list of all buckets associated with the current account. This operation is useful for getting an overview of your storage resources.
```APIDOC
## listBuckets
### Description
Lists all buckets under the current account.
### Method Signature
```javascript
listBuckets(options?: BosClientAPIOptions): BosResponse
```
### Parameters
* `options` (BosClientAPIOptions) - Optional. Request options.
### Response
* `owner` (object) - Information about the bucket owner.
* `id` (string) - Owner's user ID.
* `displayName` (string) - Owner's display name.
* `buckets` (Array