### 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) - An array of bucket objects. * `name` (string) - Bucket name. * `location` (string) - Bucket region. * `creationDate` (string) - Bucket creation date. * `enableMultiAz` (boolean) - Optional. Whether multi-AZ is enabled. * `lccLocation` (string) - Optional. LCC node ID. ### Example ```javascript const client = new BosClient({...}); client.listBuckets() .then(response => { console.log('Buckets:'); response.body.buckets.forEach(bucket => { console.log(` - ${bucket.name} (${bucket.location})`); }); }) .catch(error => { console.error('Error:', error); }); ``` ``` -------------------------------- ### Event Listener for Errors Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/01-简介与项目概览.md Example of attaching an event listener to a client to catch and log errors during requests. The 'error' event passes the error object. ```javascript client.on('error', (error) => { console.error('请求出错', error); }); ``` -------------------------------- ### Obtaining Temporary STS Credentials Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/00-文档导航.md Shows how to use the STS module to get temporary security credentials, including accessKeyId, secretAccessKey, and sessionToken, valid for a specified duration. ```javascript const {STS} = require('@baiducloud/sdk'); const sts = new STS({credentials: {...}}); const result = await sts.getSessionToken(3600); const {accessKeyId, secretAccessKey, sessionToken} = result.body; ``` -------------------------------- ### Get Object Metadata with BosClient Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/BosClient-基础操作.md Retrieves metadata for an object, such as its size and content type, without downloading the object's content. Handles potential 'NoSuchKey' errors. ```javascript const client = new BosClient({...}); client.getObjectMetadata('my-bucket', 'document.pdf') .then(response => { console.log('File size:', response.http_headers['content-length']); console.log('MIME type:', response.http_headers['content-type']); console.log('Last modified:', response.http_headers['last-modified']); }) .catch(error => { if (error['x-bce-code'] === 'NoSuchKey') { console.log('Object does not exist'); } else { console.error(error); } }); ``` -------------------------------- ### Example Usage of Result Type Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/types.md Demonstrates how to access HTTP headers and the response body from a Result object returned by an API call. The type of 'response' is inferred as Result. ```javascript const response = await client.listBuckets(); // response 的类型是 Result console.log(response.http_headers['x-bce-request-id']); console.log(response.body.buckets); ``` -------------------------------- ### Upload JSON String Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/BosClient-基础操作.md A convenience method to upload string data, automatically handling encoding. This example uploads a JSON string with the correct content type. ```javascript const client = new BosClient({...}); const jsonData = JSON.stringify({ name: 'test', timestamp: new Date().toISOString() }); client.putObjectFromString('my-bucket', 'data.json', jsonData, { 'Content-Type': 'application/json; charset=utf-8' }) .then(() => console.log('JSON uploaded')) .catch(error => console.error(error)); ``` -------------------------------- ### Delete Bucket Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/BosClient-基础操作.md Deletes a bucket. This operation requires the bucket to be empty. The example first lists and deletes all objects within the bucket before attempting to delete the bucket itself, logging success or errors. ```javascript const client = new BosClient({...}); // 删除前先清空对象 client.listObjects('my-bucket') .then(response => { // 删除所有对象 const deletePromises = response.body.contents.map(obj => client.deleteObject('my-bucket', obj.key) ); return Promise.all(deletePromises); }) .then(() => client.deleteBucket('my-bucket')) .then(() => console.log('Bucket deleted')) .catch(error => console.error(error)); ``` -------------------------------- ### Initializing BosClient Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/00-文档导航.md Shows how to initialize the BosClient with credentials, region, and protocol. Ensure your BAIDU_AK and BAIDU_SK environment variables are set. ```javascript const {BosClient} = require('@baiducloud/sdk'); const client = new BosClient({ credentials: { ak: process.env.BAIDU_AK, sk: process.env.BAIDU_SK }, region: 'bj', protocol: 'https' }); ``` -------------------------------- ### Initialize Auth Instance Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/Auth.md Instantiate the Auth tool with your Access Key (ak) and Secret Key (sk). The Secret Key should not be hardcoded in client-side code. ```javascript const {Auth} = require('@baiducloud/sdk'); const auth = new Auth('your-access-key', 'your-secret-key'); console.log(auth.ak); // your-access-key console.log(auth.sk); // your-secret-key (不应在代码中硬编码) ``` -------------------------------- ### Get Bucket ACL Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/BosClient-基础操作.md Retrieves the current Access Control List (ACL) configuration for a specified bucket. ```APIDOC ## getBucketAcl ### Description Gets the ACL of a bucket. ### Method Signature ```javascript getBucketAcl(bucketName: string, options?: BosClientAPIOptions): BosResponse ``` ### Parameters * `bucketName` (string) - Required. The name of the bucket. * `options` (BosClientAPIOptions) - Optional. Request options. ### Response * The response body contains the bucket's ACL configuration. ### Example ```javascript const client = new BosClient({...}); client.getBucketAcl('my-bucket') .then(response => { console.log('Bucket ACL:', response.body); }) .catch(error => console.error(error)); ``` ``` -------------------------------- ### 浏览器文件上传 Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/工具模块.md 在浏览器环境中,使用 BosClient 上传文件,并监听上传进度。需要引入 BaiduBCE SDK。 ```html ``` -------------------------------- ### Get Bucket ACL Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/BosClient-基础操作.md Retrieves the Access Control List (ACL) for a specified bucket. Logs the retrieved ACL on success or the error if an issue occurs. ```javascript const client = new BosClient({...}); client.getBucketAcl('my-bucket') .then(response => { console.log('Bucket ACL:', response.body); }) .catch(error => console.error(error)); ``` -------------------------------- ### constructor Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/BceBaseClient.md Initializes a BCE client instance. It takes client configuration, a service ID, and an optional boolean indicating if the service supports multiple regions. ```APIDOC ## constructor(clientConfig, serviceId, regionSupported) ### Description Initializes a BCE client instance. ### Parameters #### Path Parameters - **clientConfig** (BceClientOptions) - Required - Client configuration, including credentials, endpoint, etc. - **serviceId** (string) - Required - Service identifier, e.g., 'bos', 'cfc', 'sts', used for automatic endpoint construction. - **regionSupported** (boolean) - Optional - Whether the service supports multiple regions. If true, the endpoint will include the region; otherwise, it will not. ### Return Value BceBaseClient instance ### Example ```javascript const {BceBaseClient} = require('@baiducloud/sdk'); const client = new BceBaseClient({ credentials: { ak: 'your-ak', sk: 'your-sk' }, endpoint: 'https://bos.baidubce.com', region: 'bj' }, 'bos', true); console.log(client.config.endpoint); // Output: https://bj.bcebos.com (if endpoint is not explicitly specified) ``` ``` -------------------------------- ### Initialize BceBaseClient Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/BceBaseClient.md Instantiate a BCE client. Provide client configuration including credentials and endpoint, the service ID, and whether the service supports multiple regions. The endpoint may be auto-constructed if not explicitly provided. ```javascript const {BceBaseClient} = require('@baiducloud/sdk'); const client = new BceBaseClient({ credentials: { ak: 'your-ak', sk: 'your-sk' }, endpoint: 'https://bos.baidubce.com', region: 'bj' }, 'bos', true); console.log(client.config.endpoint); // 输出: https://bj.bcebos.com (如果 endpoint 未显式指定) ``` -------------------------------- ### Initialize BosClient Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/BosClient-基础操作.md Initializes the BosClient with provided configuration including credentials, region, endpoint, and protocol. ```javascript const {BosClient} = require('@baiducloud/sdk'); const client = new BosClient({ credentials: { ak: 'your-access-key', sk: 'your-secret-key' }, region: 'bj', // 北京地区 endpoint: 'https://bj.bcebos.com', protocol: 'https' }); ``` -------------------------------- ### Auth Constructor Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/Auth.md Initializes a new instance of the Auth signature tool with provided Access Key (ak) and Secret Key (sk). ```APIDOC ## constructor(ak, sk) ### Description Initializes a signature tool instance. ### Parameters #### Path Parameters - **ak** (string) - Required - Access Key for your Baidu Cloud account. - **sk** (string) - Required - Secret Key for your Baidu Cloud account. ### Request Example ```javascript const {Auth} = require('@baiducloud/sdk'); const auth = new Auth('your-access-key', 'your-secret-key'); console.log(auth.ak); // your-access-key console.log(auth.sk); // your-secret-key (should not be hardcoded) ``` ``` -------------------------------- ### MIT License Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/README.md The MIT license for the SDK, which also applies to this documentation. ```markdown Copyright (c) 2026 Baidu Inc. All Rights Reserved This source code is licensed under the MIT license. See LICENSE file in the project root for license information. ``` -------------------------------- ### BceClientOptions Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/types.md Constructor parameter type for all BCE service clients. ```APIDOC ## BceClientOptions ### Description Constructor parameter type for all BCE service clients. ### Type Definition ```typescript type BceClientOptions = { endpoint: string; // Service address protocol?: 'http' | 'https'; // HTTP protocol region?: string; // Region proxy?: ProxyConfig; // Proxy configuration httpObserver?: HttpObserverFn; // HTTP observer observerContext?: Record; // Observer context } & Credentials; ``` ``` -------------------------------- ### BceClientConfig Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/types.md Runtime configuration, supplemented by DEFAULT_CONFIG on top of BceClientOptions. ```APIDOC ## BceClientConfig ### Description Runtime configuration, supplemented by DEFAULT_CONFIG on top of BceClientOptions. ### Type Definition ```typescript type BceClientConfig = BceClientOptions & { protocol: 'http' | 'https'; // Must exist region: string; // Must exist pathStyleEnable?: boolean; // Path style URL }; ``` ``` -------------------------------- ### Node.js 文件上传完整流程 Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/工具模块.md 使用 BosClient 完成文件上传,包括计算 MD5、判断 MIME 类型,并设置自定义元数据。适用于 Node.js 环境。 ```javascript const {BosClient, crypto, MimeType} = require('@baiducloud/sdk'); const fs = require('fs'); async function uploadFileWithValidation(bucket, key, filepath) { const client = new BosClient({ credentials: { ak: process.env.BAIDU_AK, sk: process.env.BAIDU_SK } }); try { // 计算文件 MD5 console.log('Computing MD5...'); const md5 = await crypto.md5file(filepath, 'base64'); console.log('MD5:', md5); // 判断 MIME 类型 const contentType = MimeType.guess(key); console.log('MIME type:', contentType); // 上传文件 console.log('Uploading...'); const response = await client.putObjectFromFile(bucket, key, filepath, { 'Content-Type': contentType, 'Content-MD5': md5, 'x-bce-meta-source': 'cli', 'x-bce-meta-timestamp': new Date().toISOString() }); console.log('Upload successful'); console.log('ETag:', response.http_headers['etag']); console.log('Request ID:', response.http_headers['x-bce-request-id']); } catch (error) { console.error('Error:', error.message); } } // 使用示例 uploadFileWithValidation( 'my-bucket', 'uploads/document.pdf', '/local/document.pdf' ).catch(console.error); ``` -------------------------------- ### Listening for Client Events Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/00-文档导航.md Demonstrates how to attach event listeners to the BosClient for 'progress' and 'error' events. The 'progress' event provides loaded and total bytes, while the 'error' event captures any exceptions. ```javascript client.on('progress', (event) => { console.log(`${event.loaded} / ${event.total}`); }); client.on('error', (error) => { console.error(error); }); ``` -------------------------------- ### Importing BosClient with Type Definitions Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/00-文档导航.md Demonstrates how to import the BosClient and use type definitions for responses in both Node.js/CommonJS and TypeScript environments. ```typescript // Node.js/CommonJS const {BosClient} = require('@baiducloud/sdk'); const response: BaiduBCE.Result = await client.listBuckets(); ``` ```typescript // TypeScript import { BosClient, Result, ListBucketsRes} from '@baiducloud/sdk'; const response: Result = await client.listBuckets(); ``` -------------------------------- ### Listen for Upload/Download Progress Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/HttpClient.md Use the 'progress' event to monitor the status of uploads and downloads. The event provides the number of loaded bytes and the total bytes. ```javascript httpClient.on('progress', (event) => { console.log(event.loaded, event.total); }); ``` -------------------------------- ### 计算本地文件的 MD5 哈希值 (Node.js) Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/工具模块.md 仅在 Node.js 环境下使用,用于计算本地文件的 MD5 哈希值。内部调用 `md5stream`。 ```javascript const {crypto} = require('@baiducloud/sdk'); crypto.md5file('/path/to/file.bin', 'hex') .then(hash => { console.log('MD5:', hash); }) .catch(error => { console.error('Error reading file:', error.message); }); ``` -------------------------------- ### List Objects in a Bucket Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/BosClient-基础操作.md Use this to list objects within a bucket. Supports filtering by prefix, using delimiters for folder-like structures, and pagination. Ensure the bucket name is correct and consider the maxKeys limit. ```javascript const client = new BosClient({...}); // 列出所有对象 client.listObjects('my-bucket', {maxKeys: 100}) .then(response => { response.body.contents.forEach(obj => { console.log(`${obj.key} (${obj.size} bytes)`); }); // 如果有更多结果,继续分页 if (response.body.isTruncated) { return client.listObjects('my-bucket', { marker: response.body.nextMarker, maxKeys: 100 }); } }) .catch(error => console.error(error)); ``` ```javascript client.listObjects('my-bucket', { prefix: 'logs/', delimiter: '/', maxKeys: 100 }) .then(response => { // 列出 logs 文件夹中的对象 console.log('Objects:'); response.body.contents.forEach(obj => { console.log(` ${obj.key}`); }); // 列出 logs 文件夹中的子文件夹 console.log('Subfolders:'); response.body.commonPrefixes.forEach(prefix => { console.log(` ${prefix}`); }); }) .catch(error => console.error(error)); ``` -------------------------------- ### Include SDK via CDN Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/01-简介与项目概览.md Include the Baidu Cloud Engine JavaScript SDK in your HTML using a CDN link. ```html ``` -------------------------------- ### 计算 Blob 对象的 MD5 哈希值 (浏览器) Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/工具模块.md 仅在浏览器环境中使用,用于计算 Blob 对象的 MD5 哈希值。返回一个 Promise,解析为哈希值。 ```javascript const {crypto} = require('@baiducloud/sdk'); // 处理用户选择的文件 const fileInput = document.getElementById('file-input'); fileInput.addEventListener('change', async (event) => { const file = event.target.files[0]; const hash = await crypto.md5blob(file, 'hex'); console.log('File MD5:', hash); }); ``` -------------------------------- ### Properties Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/BceBaseClient.md Exposes configuration and service-related properties of the BceBaseClient instance. ```APIDOC ## Properties ### config ```javascript config: BceClientConfig ``` Runtime configuration object after merging default configurations. Includes: - `endpoint`: Service address - `protocol`: HTTP protocol ('http' or 'https') - `region`: Region ('bj', 'gz', etc.) - `credentials`: {ak, sk} credential pair - `sessionToken`: Optional temporary token - `pathStyleEnable`: Whether to enable path-style URLs ### serviceId ```javascript serviceId: string ``` Service identifier, such as 'bos', 'cfc', 'sts', etc. Used for automatic endpoint calculation. ### regionSupported ```javascript regionSupported: boolean ``` Indicates whether the service supports multiple regions. ### _httpAgent ```javascript _httpAgent: HttpClient | null ``` Internal HTTP client instance. Assigned after the first request is sent. ### timeOffset (static) ```javascript timeOffset?: number ``` Server time offset (milliseconds), attached to the prototype, shared across instances. Automatically adjusted when a `RequestTimeTooSkewed` error is received. ``` -------------------------------- ### 计算可读流的 MD5 哈希值 Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/工具模块.md 用于计算可读流(如大文件)的 MD5 哈希值,避免将整个文件加载到内存。返回一个 Promise,解析为哈希值。 ```javascript const {crypto} = require('@baiducloud/sdk'); const fs = require('fs'); // 计算文件 MD5 const stream = fs.createReadStream('large-file.bin'); crypto.md5stream(stream, 'hex') .then(hash => { console.log('File MD5:', hash); }) .catch(error => { console.error('Error:', error.message); }); ``` -------------------------------- ### md5file Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/工具模块.md 计算本地文件的 MD5 哈希值(仅 Node.js 环境)。此函数内部调用 `md5stream`。 ```APIDOC ## md5file ### Description 计算本地文件的 MD5 哈希值(仅 Node.js 环境)。此函数内部调用 `md5stream`。 ### Method `md5file(filename: string, digest?: string): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | 参数 | 类型 | 必需 | 默认值 | 说明 | |-----|------|------|--------|------| | filename | string | 是 | — | 文件路径 | | digest | string | 否 | 'base64' | 输出格式 | ### Returns Promise ### Example ```javascript const {crypto} = require('@baiducloud/sdk'); crypto.md5file('/path/to/file.bin', 'hex') .then(hash => { console.log('MD5:', hash); }) .catch(error => { console.error('Error reading file:', error.message); }); ``` ``` -------------------------------- ### 上传时使用 MD5 验证文件完整性 Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/工具模块.md 演示如何在上传文件时计算文件的 MD5 哈希值,并在上传请求头中包含该哈希值以进行完整性验证。 ```javascript const {BosClient, crypto} = require('@baiducloud/sdk'); async function uploadWithMD5Verification(bucket, key, file) { const client = new BosClient({...}); // 计算文件 MD5 const md5Hash = await crypto.md5blob(file, 'base64'); // 上传时包含 MD5 await client.putObject(bucket, key, file, { 'Content-MD5': md5Hash }); console.log('File uploaded with MD5:', md5Hash); } ``` -------------------------------- ### md5sum Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/工具模块.md 计算数据的 MD5 哈希值。支持字符串或 Buffer 输入,并可指定编码和输出格式。 ```APIDOC ## md5sum ### Description 计算数据的 MD5 哈希值。支持字符串或 Buffer 输入,并可指定编码和输出格式。 ### Method `md5sum(data: string | Buffer, enc?: string, digest?: string): string` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | 参数 | 类型 | 必需 | 默认值 | 说明 | |-----|------|------|--------|------| | data | string \| Buffer | 是 | — | 待哈希数据 | | enc | string | 否 | 'UTF-8' | 字符串编码方式 | | digest | string | 否 | 'base64' | 输出格式('base64' 或 'hex') | ### Returns string,哈希值 ### Example ```javascript const {crypto} = require('@baiducloud/sdk'); // 计算字符串 MD5 const hash1 = crypto.md5sum('Hello, World!'); console.log(hash1); // Base64 编码的 MD5 // 计算 Buffer 的 MD5 const buffer = Buffer.from([1, 2, 3, 4, 5]); const hash2 = crypto.md5sum(buffer, 'utf8', 'hex'); console.log(hash2); // 十六进制编码的 MD5 // 指定编码 const hash3 = crypto.md5sum('你好', 'utf8', 'hex'); console.log(hash3); // 中文字符的 MD5 ``` ``` -------------------------------- ### listObjects Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/BosClient-基础操作.md Lists objects within a bucket. Supports prefix filtering, delimiters for folder-like structures, and pagination. ```APIDOC ## listObjects(bucketName, options) ### Description Lists objects within a bucket. Supports prefix filtering, delimiters for folder-like structures, and pagination. ### Method Signature ```javascript listObjects( bucketName: string, options?: ListObjectOptions & BosClientAPIOptions ): BosResponse ``` ### Parameters #### Path Parameters - **bucketName** (string) - Required - The name of the bucket. - **options** (ListObjectOptions) - Optional - Options for listing objects. #### Options Fields - **prefix** (string) - Optional - Object name prefix for filtering. - **maxKeys** (number) - Optional - Maximum number of objects to return (default 1000, max 1000). - **marker** (string) - Optional - Pagination marker for the last object of the previous list. - **delimiter** (string) - Optional - Delimiter, typically '/' for folder functionality. ### Response #### Success Response (200) - **body** (ListObjectsRes) - The response body containing object listing details. **Response Body Structure**: ```typescript { name: string; // Bucket name prefix: string; // Query prefix marker: string; // Query pagination marker isTruncated: boolean; // Whether there are more results nextMarker: string; // Next page pagination marker maxKeys: number; // Max number of results for this request delimiter: string; // Delimiter used commonPrefixes: string[]; // Common prefixes (if delimiter is specified) contents: Array<{ eTag: string; // Object ETag key: string; // Object name lastModified: string; // Last modified time owner: {id, displayName}; size: number; // Object size in bytes storageClass: string; // Storage class }> } ``` ### Request Example ```javascript // List all objects client.listObjects('my-bucket', {maxKeys: 100}) .then(response => { response.body.contents.forEach(obj => { console.log(`${obj.key} (${obj.size} bytes)`); }); if (response.body.isTruncated) { return client.listObjects('my-bucket', { marker: response.body.nextMarker, maxKeys: 100 }); } }) .catch(error => console.error(error)); // List folder structure client.listObjects('my-bucket', { prefix: 'logs/', delimiter: '/', maxKeys: 100 }) .then(response => { console.log('Objects:'); response.body.contents.forEach(obj => { console.log(` ${obj.key}`); }); console.log('Subfolders:'); response.body.commonPrefixes.forEach(prefix => { console.log(` ${prefix}`); }); }) .catch(error => console.error(error)); ``` ``` -------------------------------- ### Browser Environment Script Inclusion Source: https://github.com/baidubce/bce-sdk-js/blob/master/docs/setup.md Include the BCE-SDK-JS in a browser environment either by importing from node_modules or via a CDN. ```html // 通过node_modules引入 // 通过CDN引入 ``` -------------------------------- ### BosClientOptions Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/types.md Configuration options for the BOS client, extending BceClientOptions with BOS-specific settings like removing version prefixes or custom URL generation. ```APIDOC ## Type: BosClientOptions ### Description Configuration options for the BOS client. ### Type Definition ```typescript type BosClientOptions = BceClientOptions & { removeVersionPrefix?: boolean; // Remove /v1 prefix customGenerateUrl?: CustomGenerateUrlFunction; // Custom URL generation }; ``` ``` -------------------------------- ### List Buckets Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/BosClient-基础操作.md Lists all buckets associated with the current account. Handles successful responses by logging bucket names and locations, and errors by logging the error. ```javascript const client = new BosClient({...}); client.listBuckets() .then(response => { console.log('Buckets:'); response.body.buckets.forEach(bucket => { console.log(` - ${bucket.name} (${bucket.location})`); }); }) .catch(error => { console.error('Error:', error); }); ``` -------------------------------- ### Download Object to Local File with BosClient Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/BosClient-基础操作.md Downloads an object from a bucket directly to a specified local file path. This is a Node.js specific operation. ```javascript const client = new BosClient({...}); client.getObjectToFile('my-bucket', 'data.csv', './downloads/data.csv') .then(() => console.log('File downloaded')) .catch(error => console.error(error)); ``` -------------------------------- ### Download Object with BosClient Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/BosClient-基础操作.md Downloads an object from a bucket. Supports downloading the entire object or a specific byte range for partial downloads or resuming interrupted transfers. ```javascript const client = new BosClient({...}); // 下载整个文件 client.getObject('my-bucket', 'document.pdf') .then(response => { console.log('File content:', response.body); console.log('MIME type:', response.http_headers['content-type']); }) .catch(error => console.error(error)); // 断点续传(下载部分内容) client.getObject('my-bucket', 'large-file.bin', { start: 1000000, // 从 1MB 处开始 end: 2000000 // 到 2MB 处 }) .then(response => { console.log('Partial content downloaded:', response.body.length); }) .catch(error => console.error(error)); ``` -------------------------------- ### Upload File with Auto Content-Type Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/工具模块.md Demonstrates how to automatically set the Content-Type header for file uploads using MimeType.guess. Ensure the BosClient and MimeType are imported. ```javascript const {BosClient, MimeType} = require('@baiducloud/sdk'); async function uploadFile(bucket, key, filepath) { const client = new BosClient({...}); const fs = require('fs'); // 自动判断 MIME 类型 const contentType = MimeType.guess(key); const fileStream = fs.createReadStream(filepath); await client.putObject(bucket, key, fileStream, { 'Content-Type': contentType }); console.log(`File uploaded as ${contentType}`); } uploadFile('my-bucket', 'documents/report.pdf', '/local/report.pdf') .catch(console.error); ``` -------------------------------- ### md5stream Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/工具模块.md 计算可读流的 MD5 哈希值。适用于计算大文件哈希,避免内存溢出。 ```APIDOC ## md5stream ### Description 计算可读流的 MD5 哈希值。适用于计算大文件哈希,避免内存溢出。 ### Method `md5stream(stream: ReadableStream, digest?: string): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | 参数 | 类型 | 必需 | 默认值 | 说明 | |-----|------|------|--------|------| | stream | ReadableStream | 是 | — | 可读流 | | digest | string | 否 | 'base64' | 输出格式 | ### Returns Promise ### Example ```javascript const {crypto} = require('@baiducloud/sdk'); const fs = require('fs'); // 计算文件 MD5 const stream = fs.createReadStream('large-file.bin'); crypto.md5stream(stream, 'hex') .then(hash => { console.log('File MD5:', hash); }) .catch(error => { console.error('Error:', error.message); }); ``` ``` -------------------------------- ### Base64 - Base64 编码 Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/工具模块.md 提供字符串的 Base64 编码和解码功能。 ```APIDOC ## Base64 - Base64 编码 **导入方式**:`require('@baiducloud/sdk').Base64` ### encode(string) ```javascript encode(string: string): string ``` 将字符串编码为 Base64。 | 参数 | 类型 | 说明 | |-----|------|------| | string | string | 待编码字符串 | **返回值**:string,Base64 编码结果 ### decode(base64String) ```javascript decode(base64String: string): string ``` 将 Base64 字符串解码为原始字符串。 | 参数 | 类型 | 说明 | |-----|------|------| | base64String | string | Base64 字符串 | **返回值**:string,解码后的字符串 **示例**: ```javascript const {Base64} = require('@baiducloud/sdk'); // 编码 const encoded = Base64.encode('Hello, World!'); console.log(encoded); // SGVsbG8sIFdvcmxkIQ== // 解码 const decoded = Base64.decode(encoded); console.log(decoded); // Hello, World! // 处理中文 const chinese = Base64.encode('你好'); console.log(Base64.decode(chinese)); // 你好 ``` ``` -------------------------------- ### Basic Error Handling with Promises Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/errors.md Demonstrates how to catch errors from a client operation using the .catch() method on a promise. It logs specific error details like 'x-bce-code', 'x-status-code', 'x-bce-request-id', and the general error message. ```javascript client.getObject('bucket', 'key') .catch(error => { console.error('Error code:', error['x-bce-code']); console.error('Status code:', error['x-status-code']); console.error('Request ID:', error['x-bce-request-id']); console.error('Message:', error.message); }); ``` -------------------------------- ### 计算字符串 MD5 哈希值 Source: https://github.com/baidubce/bce-sdk-js/blob/master/_autodocs/api-reference/工具模块.md 用于计算给定字符串的 MD5 哈希值。可以指定字符串编码和输出格式(base64 或 hex)。 ```javascript const {crypto} = require('@baiducloud/sdk'); // 计算字符串 MD5 const hash1 = crypto.md5sum('Hello, World!'); console.log(hash1); // Base64 编码的 MD5 // 计算 Buffer 的 MD5 const buffer = Buffer.from([1, 2, 3, 4, 5]); const hash2 = crypto.md5sum(buffer, 'utf8', 'hex'); console.log(hash2); // 十六进制编码的 MD5 // 指定编码 const hash3 = crypto.md5sum('你好', 'utf8', 'hex'); console.log(hash3); // 中文字符的 MD5 ```