### Install Tencent Cloud COS SDK Source: https://github.com/tencentyun/cos-nodejs-sdk-v5/blob/master/README.md Command to install the Tencent Cloud COS Node.js SDK via npm. This is a prerequisite for using the library in a Node.js project. ```shell npm i cos-nodejs-sdk-v5 --save ``` -------------------------------- ### Get Bucket Tagging - JavaScript Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Retrieves the tag configuration for a bucket. This operation requires the bucket name and region. ```javascript cos.getBucketTagging({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', }, function(err, data) { if (err) { console.log('获取标签失败:', err); } else { console.log('标签列表:', data.Tags); } }); ``` -------------------------------- ### GET List Object Versions - List Object Versions Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Retrieves a list of all versions of objects within a bucket. ```APIDOC ## GET List Object Versions /api/versions ### Description Retrieves a list of all versions of objects within a bucket. ### Method GET ### Endpoint `/{bucket}?versions` ### Parameters #### Path Parameters - **bucket** (string) - Required - The bucket name. #### Query Parameters - **region** (string) - Required - The region of the bucket. - **prefix** (string) - Optional - Filters results to objects starting with this prefix. - **max-keys** (integer) - Optional - The maximum number of versions to return per request (default is 1000). ### Response #### Success Response (200) - **Versions** (array) - A list of object versions. - **Key** (string) - The object key. - **VersionId** (string) - The version ID. - **Size** (integer) - The object size. - **LastModified** (string) - The last modified time. - **ETag** (string) - The ETag of the object version. - **IsLatest** (boolean) - Indicates if this is the latest version. - **DeleteMarkers** (array) - A list of delete markers. - **Key** (string) - The object key. - **VersionId** (string) - The version ID of the delete marker. - **LastModified** (string) - The last modified time. - **IsLatest** (boolean) - Indicates if this is the latest delete marker. #### Response Example ```json { "Versions": [ { "Key": "folder/file.txt", "VersionId": "MTg0NDY3NDI1ODU3MjQ0MTQ3Mj", "Size": 1024, "LastModified": "2023-10-27T10:00:00.000Z", "ETag": "\"etag1\"", "IsLatest": true } ], "DeleteMarkers": [ { "Key": "folder/deleted-file.txt", "VersionId": "MTg0NDY3NDI1ODU3MjQ0MTQ3Mw", "LastModified": "2023-10-27T11:00:00.000Z", "IsLatest": true } ] } ``` ``` -------------------------------- ### GET Multipart List - List Multipart Uploads Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Lists ongoing multipart upload tasks in a bucket. ```APIDOC ## GET Multipart List /api/uploads ### Description Lists ongoing multipart upload tasks in a bucket. ### Method GET ### Endpoint `/{bucket}?uploads` ### Parameters #### Path Parameters - **bucket** (string) - Required - The bucket name. #### Query Parameters - **region** (string) - Required - The region of the bucket. - **prefix** (string) - Optional - Filters uploads by prefix. ### Response #### Success Response (200) - **Upload** (array) - A list of ongoing multipart upload tasks. - **Key** (string) - The object key. - **UploadId** (string) - The upload ID. - **Initiated** (string) - The initiation time of the upload. #### Response Example ```json { "Upload": [ { "Key": "folder/large-file.zip", "UploadId": "example-upload-id-12345", "Initiated": "2023-10-27T12:00:00.000Z" } ] } ``` ``` -------------------------------- ### GET Object API Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Downloads an object from a bucket, supporting range downloads and conditional downloads. ```APIDOC ## GET Object ### Description Downloads an object from a bucket. Supports range downloads and conditional downloads. ### Method GET ### Endpoint `/{bucket}/{key}` ### Parameters #### Path Parameters - **Bucket** (string) - Required - The name of the bucket. - **Key** (string) - Required - The key (name) of the object to download. - **Region** (string) - Required - The region of the bucket. #### Query Parameters - **Range** (string) - Optional - Specifies the byte range to download (e.g., 'bytes=0-1023'). #### Request Body - **Output** (Stream | string) - Required - Specifies where to write the downloaded content (e.g., a writable stream or a file path). - **onProgress** (function) - Optional - Callback function to track download progress. ### Request Example ```javascript var fs = require('fs'); cos.getObject({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', Key: 'folder/example.txt', Output: fs.createWriteStream('./download.txt'), // Or specify a file path // Range: 'bytes=0-1023', // Optional, specify download range onProgress: function(progressData) { console.log('下载进度:', JSON.stringify(progressData)); }, }, function(err, data) { if (err) { console.log('下载失败:', err); } else { console.log('下载成功,ETag:', data.ETag); } }); ``` ### Response #### Success Response (200) - **ETag** (string) - The ETag of the downloaded object. - **Headers** (object) - Contains response headers, including Content-Type, Content-Length, etc. #### Response Example (Response body content depends on the object being downloaded. Success response typically includes ETag and headers.) ``` -------------------------------- ### GET Object Tagging - Get Object Tags Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Retrieves the tags associated with an object. ```APIDOC ## GET Object Tagging /api/objects/tagging ### Description Retrieves the tags associated with an object. ### Method GET ### Endpoint `/{bucket}/{key}?tagging` ### Parameters #### Path Parameters - **bucket** (string) - Required - The bucket name. - **key** (string) - Required - The object key. #### Query Parameters - **region** (string) - Required - The region of the bucket. ### Response #### Success Response (200) - **Tags** (array) - A list of tags associated with the object. - **Key** (string) - The tag key. - **Value** (string) - The tag value. #### Response Example ```json { "Tags": [ { "Key": "type", "Value": "document" }, { "Key": "status", "Value": "active" } ] } ``` ``` -------------------------------- ### GET Bucket CORS - Get Cross-Origin Access Configuration Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Retrieves the Cross-Origin Resource Sharing (CORS) configuration rules for a bucket. ```APIDOC ## GET Bucket CORS - Get Cross-Origin Access Configuration ### Description Retrieves the Cross-Origin Resource Sharing (CORS) configuration rules for a bucket. ### Method GET ### Endpoint `/{BucketName}?cors` ### Parameters #### Path Parameters - **Bucket** (string) - Required - The name of the bucket. #### Query Parameters - **Region** (string) - Optional - The region of the bucket. #### Request Body None ### Request Example ```javascript cos.getBucketCors({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', }, function(err, data) { if (err) { console.log('Failed to get CORS configuration:', err); } else { console.log('CORS rules:', data.CORSRules); } }); ``` ### Response #### Success Response (200) - **CORSRules** (array) - An array of CORS rule objects. #### Response Example ```json { "CORSRules": [ { "AllowedOrigins": ["http://example.com", "https://example.com"], "AllowedMethods": ["GET", "PUT", "POST", "DELETE", "HEAD"], "AllowedHeaders": ["*"], "ExposeHeaders": ["ETag", "x-cos-request-id"], "MaxAgeSeconds": 600 } ] } ``` ``` -------------------------------- ### GET Service - List Buckets Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Retrieves a list of all buckets associated with your account, with options for filtering by tags or creation time. ```APIDOC ## GET Service - List Buckets ### Description Retrieves a list of all buckets associated with your account, with options for filtering by tags or creation time. ### Method GET ### Endpoint / ### Parameters #### Query Parameters - **Region** (string) - Optional - The region to list buckets from. #### Request Body None ### Request Example ```javascript cos.getService({ Region: 'ap-beijing', // Optional, specify region }, function(err, data) { if (err) { console.log('Failed to get bucket list:', err); } else { console.log('Bucket list:', data.Buckets); } }); ``` ### Response #### Success Response (200) - **Buckets** (array) - An array of bucket objects, each containing Name, Region, and CreationDate. #### Response Example ```json { "Buckets": [ { "Name": "examplebucket-1250000000", "Region": "ap-beijing", "CreationDate": "2023-01-01T10:00:00.000Z" } ] } ``` ``` -------------------------------- ### GET Object ACL - Get Object Access Permissions Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Retrieves the Access Control List (ACL) configuration for an object. ```APIDOC ## GET Object ACL /api/objects/acl ### Description Retrieves the Access Control List (ACL) configuration for an object. ### Method GET ### Endpoint `/{bucket}/{key}?acl` ### Parameters #### Path Parameters - **bucket** (string) - Required - The bucket name. - **key** (string) - Required - The object key. #### Query Parameters - **region** (string) - Required - The region of the bucket. ### Response #### Success Response (200) - **ACL** (string) - The ACL configuration of the object (e.g., `private`, `public-read`). - **Owner** (object) - Information about the object owner. - **ID** (string) - The owner's ID. - **Grants** (array) - A list of grants specifying permissions for users or groups. - **Grantee** (object) - Information about the grantee. - **Type** (string) - The type of grantee (e.g., `CanonicalUser`, `Group`). - **ID** (string) - The grantee's ID (if `Type` is `CanonicalUser`). - **URI** (string) - The grantee's URI (if `Type` is `Group`). - **Permission** (string) - The permission granted (e.g., `READ`, `WRITE`, `FULL_CONTROL`). #### Response Example ```json { "ACL": "public-read", "Owner": { "ID": "100000000001" }, "Grants": [ { "Grantee": { "Type": "Group", "URI": "http://acs.amazonaws.com/groups/global/AllUsers" }, "Permission": "READ" } ] } ``` ``` -------------------------------- ### Get Bucket Versioning Status - JavaScript Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Retrieves the versioning configuration status of a bucket. This operation requires the bucket name and region. ```javascript cos.getBucketVersioning({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', }, function(err, data) { if (err) { console.log('获取版本控制状态失败:', err); } else { console.log('版本控制状态:', data.VersioningConfiguration.Status); } }); ``` -------------------------------- ### GET Bucket ACL - Get Bucket Access Permissions Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Retrieves the Access Control List (ACL) configuration for a bucket, including owner and grant information. ```APIDOC ## GET Bucket ACL - Get Bucket Access Permissions ### Description Retrieves the Access Control List (ACL) configuration for a bucket, including owner and grant information. ### Method GET ### Endpoint `/{BucketName}?acl` ### Parameters #### Path Parameters - **Bucket** (string) - Required - The name of the bucket. #### Query Parameters - **Region** (string) - Optional - The region of the bucket. #### Request Body None ### Request Example ```javascript cos.getBucketAcl({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', }, function(err, data) { if (err) { console.log('Failed to get ACL:', err); } else { console.log('ACL:', data.ACL); console.log('Owner:', data.Owner); console.log('Grants:', data.Grants); } }); ``` ### Response #### Success Response (200) - **ACL** (string) - The ACL configuration (e.g., `private`, `public-read`). - **Owner** (object) - Information about the bucket owner. - **Grants** (array) - An array of grant objects, specifying permissions for users. #### Response Example ```json { "ACL": "public-read", "Owner": { "DisplayName": "user1", "ID": "100000000001" }, "Grants": [ { "Grantee": { "ID": "100000000001", "DisplayName": "user1" }, "Permission": "FULL_CONTROL" } ] } ``` ``` -------------------------------- ### GET /bucket/policy Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Retrieves the current access control policy for a bucket. ```APIDOC ## GET /bucket/policy ### Description Fetches the existing policy configuration for the specified bucket. ### Method GET ### Parameters #### Query Parameters - **Bucket** (string) - Required - The name of the bucket - **Region** (string) - Required - The bucket region ``` -------------------------------- ### Get Object Metadata Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Retrieves the metadata of an object without downloading the actual content. ```javascript cos.headObject({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', Key: 'folder/example.txt', }, function(err, data) { if (err) { console.log('获取元数据失败:', err); } else { console.log('Content-Length:', data.headers['content-length']); console.log('Content-Type:', data.headers['content-type']); console.log('ETag:', data.ETag); console.log('Last-Modified:', data.headers['last-modified']); } }); ``` -------------------------------- ### Get Bucket Policy - JavaScript Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Retrieves the access policy configuration for a bucket. This operation requires the bucket name and region. ```javascript cos.getBucketPolicy({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', }, function(err, data) { if (err) { console.log('获取存储桶策略失败:', err); } else { console.log('存储桶策略:', data.Policy); } }); ``` -------------------------------- ### GET Bucket - List Objects Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Retrieves a list of objects within a bucket, supporting prefix filtering, pagination, and hierarchical display. ```APIDOC ## GET Bucket - List Objects ### Description Retrieves a list of objects within a bucket, supporting prefix filtering, pagination, and hierarchical display. ### Method GET ### Endpoint `/{BucketName}` ### Parameters #### Path Parameters - **Bucket** (string) - Required - The name of the bucket. #### Query Parameters - **Region** (string) - Optional - The region of the bucket. - **Prefix** (string) - Optional - Filters objects by a specified prefix. - **Delimiter** (string) - Optional - A delimiter to simulate folder structures. - **MaxKeys** (number) - Optional - The maximum number of objects to return. - **Marker** (string) - Optional - A marker for pagination. #### Request Body None ### Request Example ```javascript cos.getBucket({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', Prefix: 'folder/', // Optional, object key prefix Delimiter: '/', // Optional, delimiter for simulating folders MaxKeys: 1000, // Optional, maximum number of returned items Marker: '', // Optional, pagination marker }, function(err, data) { if (err) { console.log('Failed to get object list:', err); } else { console.log('Object list:', data.Contents); console.log('Common prefixes (subfolders):', data.CommonPrefixes); } }); ``` ### Response #### Success Response (200) - **Contents** (array) - An array of object details (Key, LastModified, ETag, Size, StorageClass). - **CommonPrefixes** (array) - An array of common prefixes (simulated folders). #### Response Example ```json { "Contents": [ { "Key": "folder/object.txt", "LastModified": "2023-01-01T10:00:00.000Z", "ETag": "\"abcdef1234567890\"", "Size": 1024, "StorageClass": "STANDARD" } ], "CommonPrefixes": [ { "Prefix": "folder/subfolder/" } ] } ``` ``` -------------------------------- ### getObjectUrl - Get Object Access URL Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Generates a pre-signed URL for accessing an object, with support for setting expiration times. ```APIDOC ## getObjectUrl ### Description Generates a pre-signed URL for accessing an object. ### Parameters #### Request Body - **Bucket** (string) - Required - Bucket name. - **Region** (string) - Required - Bucket region. - **Key** (string) - Required - Object key. - **Sign** (boolean) - Optional - Whether to include a signature. - **Expires** (number) - Optional - Expiration time in seconds. - **Method** (string) - Optional - HTTP method (e.g., GET). ### Response #### Success Response (200) - **Url** (string) - The generated pre-signed URL. ### Response Example { "Url": "https://examplebucket-1250000000.cos.ap-beijing.myqcloud.com/folder/example.txt?q-sign-algorithm=..." } ``` -------------------------------- ### Get Bucket Lifecycle Rule - JavaScript Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Retrieves the lifecycle management rules configured for a bucket. This operation requires the bucket name and region. ```javascript cos.getBucketLifecycle({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', }, function(err, data) { if (err) { console.log('获取生命周期规则失败:', err); } else { console.log('生命周期规则:', data.Rules); } }); ``` -------------------------------- ### Get Object URL - getObjectUrl Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Generates a pre-signed URL for accessing an object, with support for setting an expiration time. This allows temporary, secure access to objects without public read permissions. ```javascript var url = cos.getObjectUrl({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', Key: 'folder/example.txt', Sign: true, // 是否需要签名 Expires: 3600, // 签名有效期,单位秒 Method: 'GET', // 请求方法 }, function(err, data) { if (err) { console.log('获取URL失败:', err); } else { console.log('预签名URL:', data.Url); } }); // 同步返回URL console.log('同步URL:', url); ``` -------------------------------- ### Configure Bucket Logging Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Sets up access logging for a bucket, directing logs to a specified target bucket. Requires bucket and region parameters. ```javascript cos.putBucketLogging({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', BucketLoggingStatus: { LoggingEnabled: { TargetBucket: 'logbucket-1250000000', TargetPrefix: 'logs/', }, }, }, function(err, data) { if (err) { console.log('设置日志管理失败:', err); } else { console.log('日志管理设置成功'); } }); ``` -------------------------------- ### Set Static Website - JavaScript Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Configures a bucket for static website hosting, specifying index and error documents. Requires bucket name, region, and website configuration. ```javascript cos.putBucketWebsite({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', WebsiteConfiguration: { IndexDocument: { Suffix: 'index.html' }, ErrorDocument: { Key: 'error.html' }, RedirectAllRequestsTo: { Protocol: 'https', }, }, }, function(err, data) { if (err) { console.log('设置静态网站失败:', err); } else { console.log('静态网站设置成功'); } }); ``` -------------------------------- ### Initialize Client and Upload File Source: https://github.com/tencentyun/cos-nodejs-sdk-v5/blob/master/README.md Demonstrates how to initialize the COS client using SecretId and SecretKey, and how to perform an advanced file upload. The uploadFile method automatically handles multipart uploads based on the specified SliceSize. ```javascript var COS = require('cos-nodejs-sdk-v5'); var cos = new COS({ SecretId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', SecretKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', }); var Bucket = 'test-1250000000'; var Region = 'ap-guangzhou'; cos.uploadFile( { Bucket: Bucket, Region: Region, Key: '1.zip', FilePath: './1.zip', SliceSize: 1024 * 1024 * 5, }, function (err, data) { console.log(err, data); } ); ``` -------------------------------- ### Initialization Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Initializes the COS client instance with your SecretId, SecretKey, and optional configuration parameters. ```APIDOC ## Initialization ### Description Initializes the COS client instance with your SecretId, SecretKey, and optional configuration parameters. ### Method Constructor ### Endpoint N/A ### Parameters #### Request Body - **SecretId** (string) - Required - Your Tencent Cloud SecretId. - **SecretKey** (string) - Required - Your Tencent Cloud SecretKey. - **FileParallelLimit** (number) - Optional - Maximum number of files to upload concurrently. - **ChunkParallelLimit** (number) - Optional - Maximum number of chunks to upload concurrently for a single file. - **ChunkSize** (number) - Optional - Size of each chunk in bytes for chunked uploads. - **Protocol** (string) - Optional - The request protocol (e.g., 'https:'). - **Timeout** (number) - Optional - Request timeout in milliseconds. ### Request Example ```javascript var COS = require('cos-nodejs-sdk-v5'); var cos = new COS({ SecretId: 'AKID********************************', SecretKey: '********************************', // Optional configuration FileParallelLimit: 3, ChunkParallelLimit: 3, ChunkSize: 1024 * 1024, Protocol: 'https:', Timeout: 60000, }); ``` ### Response N/A (Initialization does not return a response in the traditional sense.) ``` -------------------------------- ### POST Multipart Init - Initialize Multipart Upload Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Initializes a multipart upload task and retrieves an upload ID. ```APIDOC ## POST Multipart Init /api/uploads ### Description Initializes a multipart upload task and retrieves an upload ID. ### Method POST ### Endpoint `/{bucket}/{key}?uploads` ### Parameters #### Path Parameters - **bucket** (string) - Required - The bucket name. - **key** (string) - Required - The object key for the upload. #### Query Parameters - **region** (string) - Required - The region of the bucket. - **ContentType** (string) - Optional - The content type of the object. - **ACL** (string) - Optional - The ACL for the uploaded object. ### Response #### Success Response (200) - **UploadId** (string) - The unique ID for the multipart upload task. #### Response Example ```json { "UploadId": "example-upload-id-12345" } ``` ``` -------------------------------- ### Manage Storage Buckets Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Operations to list, create, check existence, and delete storage buckets. These methods require the bucket name and region parameters. ```javascript cos.getService({ Region: 'ap-beijing' }, function(err, data) { ... }); cos.putBucket({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', ACL: 'public-read' }, function(err, data) { ... }); cos.headBucket({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing' }, function(err, data) { ... }); cos.deleteBucket({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing' }, function(err, data) { ... }); ``` -------------------------------- ### Initialize COS Client Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Creates a new COS client instance using your SecretId and SecretKey. Optional parameters like concurrency limits and timeouts can be configured during initialization. ```javascript var COS = require('cos-nodejs-sdk-v5'); var cos = new COS({ SecretId: 'AKID********************************', SecretKey: '********************************', FileParallelLimit: 3, ChunkParallelLimit: 3, ChunkSize: 1024 * 1024, Protocol: 'https:', Timeout: 60000, }); ``` -------------------------------- ### Download File to Local - downloadFile Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt An advanced interface for downloading files to local storage with support for resumable downloads. It allows configuration of chunk size and parallel download limits for optimized performance. ```javascript cos.downloadFile({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', Key: 'folder/large-file.zip', FilePath: './download/large-file.zip', ChunkSize: 1024 * 1024 * 5, // 分块大小 ParallelLimit: 5, // 并发下载数 onProgress: function(progressData) { console.log('下载进度:', JSON.stringify(progressData)); }, }, function(err, data) { if (err) { console.log('下载失败:', err); } else { console.log('下载成功'); } }); ``` -------------------------------- ### Set Bucket Replication - JavaScript Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Configures cross-region replication rules for a bucket to ensure data backup in different regions. Requires bucket name, region, and replication configuration details. ```javascript cos.putBucketReplication({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', ReplicationConfiguration: { Role: 'qcs::cam::uin/100000000001:uin/100000000001', Rules: [{ ID: 'replication-rule-1', Status: 'Enabled', Prefix: '', Destination: { Bucket: 'qcs::cos:ap-guangzhou::destbucket-1250000000', StorageClass: 'STANDARD', }, }], }, }, function(err, data) { if (err) { console.log('设置跨地域复制失败:', err); } else { console.log('跨地域复制设置成功'); } }); ``` -------------------------------- ### PUT Bucket - Create Bucket Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Creates a new bucket, allowing you to specify the region, access control list (ACL), and multi-availability zone configuration. ```APIDOC ## PUT Bucket - Create Bucket ### Description Creates a new bucket, allowing you to specify the region, access control list (ACL), and multi-availability zone configuration. ### Method PUT ### Endpoint `/{BucketName}` ### Parameters #### Path Parameters - **Bucket** (string) - Required - The name of the bucket to create. #### Query Parameters - **Region** (string) - Required - The region where the bucket will be created. #### Request Body - **ACL** (string) - Optional - The ACL configuration for the bucket. Allowed values: `private`, `public-read`, `public-read-write`. ### Request Example ```javascript cos.putBucket({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', ACL: 'public-read', // Optional values: private, public-read, public-read-write }, function(err, data) { if (err) { console.log('Failed to create bucket:', err); } else { console.log('Bucket created successfully, Location:', data.Location); } }); ``` ### Response #### Success Response (200) - **Location** (string) - The URL of the newly created bucket. #### Response Example ```json { "Location": "http://examplebucket-1250000000.cos.ap-beijing.myqcloud.com" } ``` ``` -------------------------------- ### Multipart Upload Lifecycle Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Handles the complete multipart upload process: initializing, uploading parts, completing, aborting, and listing active tasks. ```javascript var fs = require('fs'); cos.multipartInit({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', Key: 'folder/large-file.zip', ContentType: 'application/zip', ACL: 'public-read', }, function(err, data) { if (err) { console.log('初始化分块上传失败:', err); } else { console.log('上传ID:', data.UploadId); } }); cos.multipartUpload({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', Key: 'folder/large-file.zip', UploadId: 'upload-id-from-init', PartNumber: 1, Body: fs.createReadStream('./part1.dat'), ContentLength: 5 * 1024 * 1024, }, function(err, data) { if (err) { console.log('上传分块失败:', err); } else { console.log('分块上传成功,ETag:', data.ETag); } }); cos.multipartComplete({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', Key: 'folder/large-file.zip', UploadId: 'upload-id-from-init', Parts: [ { PartNumber: 1, ETag: '"etag1"' }, { PartNumber: 2, ETag: '"etag2"' }, { PartNumber: 3, ETag: '"etag3"' }, ], }, function(err, data) { if (err) { console.log('完成分块上传失败:', err); } else { console.log('分块上传完成,Location:', data.Location); } }); cos.multipartAbort({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', Key: 'folder/large-file.zip', UploadId: 'upload-id-from-init', }, function(err, data) { if (err) { console.log('取消分块上传失败:', err); } else { console.log('分块上传已取消'); } }); cos.multipartList({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', Prefix: 'folder/', }, function(err, data) { if (err) { console.log('获取分块上传列表失败:', err); } else { console.log('分块上传任务:', data.Upload); } }); ``` -------------------------------- ### List Object Versions Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Retrieves all version information for objects within a bucket, including delete markers. ```javascript cos.listObjectVersions({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', Prefix: 'folder/', MaxKeys: 1000, }, function(err, data) { if (err) { console.log('获取对象版本列表失败:', err); } else { console.log('对象版本:', data.Versions); console.log('删除标记:', data.DeleteMarkers); } }); ``` -------------------------------- ### Configure Bucket Inventory Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Creates an inventory task to periodically generate object reports. It supports filtering and specifying optional metadata fields. ```javascript cos.putBucketInventory({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', Id: 'inventory-config-1', InventoryConfiguration: { Id: 'inventory-config-1', IsEnabled: 'true', Destination: { COSBucketDestination: { Format: 'CSV', AccountId: '100000000001', Bucket: 'qcs::cos:ap-beijing::inventorybucket-1250000000', Prefix: 'inventory/', }, }, Schedule: { Frequency: 'Daily' }, Filter: { Prefix: 'data/' }, IncludedObjectVersions: 'Current', OptionalFields: ['Size', 'LastModifiedDate', 'ETag', 'StorageClass'], }, }, function(err, data) { if (err) { console.log('设置清单任务失败:', err); } else { console.log('清单任务设置成功'); } }); ``` -------------------------------- ### Configure Global Acceleration Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Enables or suspends global acceleration for a bucket to improve cross-region access speeds. ```javascript cos.putBucketAccelerate({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', AccelerateConfiguration: { Status: 'Enabled', }, }, function(err, data) { if (err) { console.log('设置全球加速失败:', err); } else { console.log('全球加速设置成功'); } }); ``` -------------------------------- ### PUT /bucket/tagging Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Configures tags for a bucket for classification and cost management. ```APIDOC ## PUT /bucket/tagging ### Description Applies tags to a bucket to help with resource organization. ### Method PUT ### Parameters #### Request Body - **Bucket** (string) - Required - The name of the bucket - **Region** (string) - Required - The bucket region - **Tags** (array) - Required - List of key-value tag objects ``` -------------------------------- ### Smart Upload - uploadFile Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt An advanced interface that intelligently selects between simple upload and multipart upload based on file size. It simplifies the upload process by handling the logic automatically. ```javascript cos.uploadFile({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', Key: 'folder/example.txt', FilePath: './local-file.txt', SliceSize: 1024 * 1024 * 5, // 大于5MB使用分块上传 onTaskReady: function(taskId) { console.log('任务ID:', taskId); }, onProgress: function(progressData) { console.log('上传进度:', JSON.stringify(progressData)); }, }, function(err, data) { if (err) { console.log('上传失败:', err); } else { console.log('上传成功,Location:', data.Location); } }); ``` -------------------------------- ### Set Referer - JavaScript Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Configures referer protection for a bucket to restrict access from unauthorized referrers. Requires bucket name, region, and referer configuration. ```javascript cos.putBucketReferer({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', RefererConfiguration: { Status: 'Enabled', RefererType: 'White-List', DomainList: { Domains: ['*.example.com', 'example.com'], }, EmptyReferConfiguration: 'Deny', }, }, function(err, data) { if (err) { console.log('设置防盗链失败:', err); } else { console.log('防盗链设置成功'); } }); ``` -------------------------------- ### Batch Upload Files - uploadFiles Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt An advanced interface for uploading multiple files in batches, automatically managing concurrency. This is ideal for uploading collections of files efficiently. ```javascript cos.uploadFiles({ files: [ { Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', Key: 'folder/file1.txt', FilePath: './local-file1.txt', }, { Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', Key: 'folder/file2.txt', FilePath: './local-file2.txt', }, ], SliceSize: 1024 * 1024 * 5, onProgress: function(info) { console.log('总进度:', JSON.stringify(info)); }, onFileFinish: function(err, data, options) { console.log('文件完成:', options.Key, err ? '失败' : '成功'); }, }, function(err, data) { if (err) { console.log('批量上传出错:', err); } else { console.log('批量上传完成'); } }); ``` -------------------------------- ### Download Object Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Downloads an object from a bucket to a local file stream. Supports range-based downloads. ```javascript var fs = require('fs'); cos.getObject({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', Key: 'folder/example.txt', Output: fs.createWriteStream('./download.txt'), onProgress: function(progressData) { console.log('下载进度:', JSON.stringify(progressData)); }, }, function(err, data) { if (err) { console.log('下载失败:', err); } else { console.log('下载成功,ETag:', data.ETag); } }); ``` -------------------------------- ### POST Object API Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Uploads a single object to a bucket, with support for setting metadata, permissions, and storage class. ```APIDOC ## POST Object ### Description Uploads a single object to a bucket. Supports setting metadata, permissions, and storage class. ### Method POST ### Endpoint `/{bucket}` ### Parameters #### Path Parameters - **Bucket** (string) - Required - The name of the bucket. #### Request Body - **Body** (Stream | Buffer | string) - Required - The content of the object to upload. - **Key** (string) - Required - The key (name) of the object. - **Region** (string) - Required - The region of the bucket. - **ContentLength** (number) - Required - The size of the object content in bytes. - **ContentType** (string) - Optional - The MIME type of the object. - **ACL** (string) - Optional - The Access Control List for the object (e.g., 'private', 'public-read'). - **StorageClass** (string) - Optional - The storage class for the object (e.g., 'STANDARD', 'STANDARD_IA', 'ARCHIVE'). - **Metadata** (object) - Optional - Custom metadata for the object, prefixed with 'x-cos-meta-'. - **x-cos-meta-author** (string) - Example custom metadata field. - **onProgress** (function) - Optional - Callback function to track upload progress. ### Request Example ```javascript var fs = require('fs'); cos.putObject({ Bucket: 'examplebucket-1250000000', Region: 'ap-beijing', Key: 'folder/example.txt', Body: fs.createReadStream('./local-file.txt'), // Or Buffer or string ContentLength: fs.statSync('./local-file.txt').size, ContentType: 'text/plain', ACL: 'public-read', StorageClass: 'STANDARD', Metadata: { 'x-cos-meta-author': 'test', }, onProgress: function(progressData) { console.log('上传进度:', JSON.stringify(progressData)); }, }, function(err, data) { if (err) { console.log('上传失败:', err); } else { console.log('上传成功,ETag:', data.ETag); console.log('访问地址:', data.Location); } }); ``` ### Response #### Success Response (200) - **ETag** (string) - The ETag of the uploaded object. - **Location** (string) - The URL of the uploaded object. #### Response Example ```json { "ETag": "\"a1b2c3d4e5f678901234567890abcdef\"", "Location": "http://examplebucket-1250000000.cos.ap-beijing.myqcloud.com/folder/example.txt" } ``` ``` -------------------------------- ### PUT Bucket Logging API Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Configures access logging for a bucket, directing logs to a specified target bucket. ```APIDOC ## PUT Bucket Logging ### Description Sets up access logging for a bucket, enabling logs to be delivered to a specified target bucket. ### Method PUT ### Endpoint `/{bucket}/?logging` ### Parameters #### Query Parameters - **logging** (string) - Required - Specifies the logging configuration. #### Request Body - **BucketLoggingStatus** (object) - Required - The logging status configuration. - **LoggingEnabled** (object) - Required - Configuration for enabling logging. - **TargetBucket** (string) - Required - The bucket where logs will be stored. - **TargetPrefix** (string) - Optional - The prefix for log objects within the target bucket. ### Request Example ```json { "Bucket": "examplebucket-1250000000", "Region": "ap-beijing", "BucketLoggingStatus": { "LoggingEnabled": { "TargetBucket": "logbucket-1250000000", "TargetPrefix": "logs/" } } } ``` ### Response #### Success Response (200) - **Headers** (object) - Contains response headers. #### Response Example (No specific response body example provided for this operation, typically an empty body on success.) ``` -------------------------------- ### PUT /bucket/lifecycle Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Configures lifecycle rules for automatic object expiration or storage class transitions. ```APIDOC ## PUT /bucket/lifecycle ### Description Sets lifecycle rules to automate data management tasks like deletion or archiving. ### Method PUT ### Parameters #### Request Body - **Bucket** (string) - Required - The name of the bucket - **Region** (string) - Required - The bucket region - **Rules** (array) - Required - Lifecycle rule configurations ``` -------------------------------- ### multipartListPart - List Uploaded Parts Source: https://context7.com/tencentyun/cos-nodejs-sdk-v5/llms.txt Lists the parts that have been uploaded for a specific multipart upload task. ```APIDOC ## multipartListPart ### Description Lists the parts that have been uploaded for a specific multipart upload task. ### Method POST/GET (SDK abstraction) ### Parameters #### Request Body - **Bucket** (string) - Required - The name of the bucket. - **Region** (string) - Required - The region of the bucket. - **Key** (string) - Required - The object key. - **UploadId** (string) - Required - The upload ID obtained from the initialization. ### Response #### Success Response (200) - **Part** (array) - List of uploaded parts. ### Response Example { "Part": [{ "PartNumber": 1, "ETag": "..." }] } ```