### Install SDK from Local .tgz Source: https://github.com/tencentcloud/tencentcloud-sdk-nodejs/blob/master/README.md Install the SDK into your project from a locally generated .tgz file. ```bash npm install /path/to/tencentcloud-sdk-nodejs/tencentcloud-sdk-nodejs-4.0.0.tgz ``` -------------------------------- ### Install VPC SDK via npm Source: https://github.com/tencentcloud/tencentcloud-sdk-nodejs/blob/master/README.md Install the VPC SDK using npm. This is the recommended method for installing specific product SDKs. ```bash npm install tencentcloud-sdk-nodejs-vpc --save ``` -------------------------------- ### Installation Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Instructions for installing the Tencent Cloud SDK for Node.js, including options for specific products, the full SDK, slim SDK, and common client. ```APIDOC ## Installation Install the SDK via npm for specific products (recommended) or the full SDK package. ```bash # Install specific product SDK (recommended for smaller bundle size) npm install tencentcloud-sdk-nodejs-cvm --save npm install tencentcloud-sdk-nodejs-vpc --save npm install tencentcloud-sdk-nodejs-hunyuan --save # Install full SDK (all products) npm install tencentcloud-sdk-nodejs --save # Install slim SDK (smaller bundle, no TypeScript definitions) npm install tencentcloud-sdk-slim-nodejs --save # Install Common Client only (for generic API calls) npm install tencentcloud-sdk-nodejs-common --save ``` ``` -------------------------------- ### Install CVM SDK via npm Source: https://github.com/tencentcloud/tencentcloud-sdk-nodejs/blob/master/README.md Install the CVM SDK using npm. This is the recommended method for installing specific product SDKs. ```bash npm install tencentcloud-sdk-nodejs-cvm --save ``` -------------------------------- ### TypeScript Import Example Source: https://github.com/tencentcloud/tencentcloud-sdk-nodejs/blob/master/README.md Example of how to import and use the SDK in a TypeScript project. ```javascript import * as tencentcloud from "tencentcloud-sdk-nodejs" const CvmClient = tencentcloud.cvm.v20170312.Client // ... ``` -------------------------------- ### Install Specific Product SDKs Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Install SDKs for individual Tencent Cloud products via npm for a smaller bundle size. This is the recommended approach. ```bash npm install tencentcloud-sdk-nodejs-cvm --save npm install tencentcloud-sdk-nodejs-vpc --save npm install tencentcloud-sdk-nodejs-hunyuan --save ``` -------------------------------- ### Install Full Product SDK via npm Source: https://github.com/tencentcloud/tencentcloud-sdk-nodejs/blob/master/README.md Install the SDK that includes all cloud product SDKs. This is suitable for projects that depend on many cloud products but may result in a larger package size. ```bash npm install tencentcloud-sdk-nodejs --save ``` -------------------------------- ### Build SDK from Source Source: https://github.com/tencentcloud/tencentcloud-sdk-nodejs/blob/master/README.md After cloning the SDK source code, run npm install and npm run build in the project root directory to build the SDK. ```bash npm install && npm run build ``` -------------------------------- ### Install Common Client Only Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Install only the common client package, which is useful for making generic API calls without specific service modules. ```bash npm install tencentcloud-sdk-nodejs-common --save ``` -------------------------------- ### Install Slim Version SDK via npm Source: https://github.com/tencentcloud/tencentcloud-sdk-nodejs/blob/master/README.md Install the Slim version of the SDK for projects sensitive to package size. This version removes type files and includes code compression. ```bash npm install tencentcloud-sdk-slim-nodejs --save ``` -------------------------------- ### Client Configuration Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Example of how to configure the Tencent Cloud SDK client with authentication credentials and optional settings. ```APIDOC ## Client Configuration The ClientConfig interface defines authentication credentials and optional settings for all service clients. ```typescript import { cvm } from "tencentcloud-sdk-nodejs-cvm" const CvmClient = cvm.v20170312.Client // Full configuration example const client = new CvmClient({ // Required: Authentication credentials credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, // Optional: For temporary credentials (STS) token: process.env.TENCENTCLOUD_TOKEN, }, // Required for regional services, optional for global services region: "ap-shanghai", // Optional: Advanced configuration profile: { signMethod: "TC3-HMAC-SHA256", // Signature method language: "en-US", // API response language: "zh-CN" | "en-US" httpProfile: { reqMethod: "POST", // HTTP method: "POST" | "GET" reqTimeout: 60, // Request timeout in seconds endpoint: "cvm.tencentcloudapi.com", // Custom endpoint protocol: "https://", // Protocol proxy: "http://127.0.0.1:8899", // HTTP proxy headers: { "X-TC-TraceId": "custom-trace-id", // Custom headers }, }, }, }) ``` ``` -------------------------------- ### Initialize CVM Client and Call API Source: https://github.com/tencentcloud/tencentcloud-sdk-nodejs/blob/master/README.md Example of initializing a CVM client and calling the DescribeZones API. It demonstrates how to configure credentials, region, and other client options. It's recommended to manage credentials via environment variables for security. ```javascript const tencentcloud = require("tencentcloud-sdk-nodejs") // 导入对应产品模块的client models。 const CvmClient = tencentcloud.cvm.v20170312.Client // 实例化要请求产品(以cvm为例)的client对象 const client = new CvmClient({ // 为了保护密钥安全,建议将密钥设置在环境变量中或者配置文件中,请参考本文凭证管理章节。 // 硬编码密钥到代码中有可能随代码泄露而暴露,有安全隐患,并不推荐。 credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, }, // 产品地域 region: "ap-shanghai", // 可选配置实例 profile: { signMethod: "TC3-HMAC-SHA256", // 签名方法 httpProfile: { reqMethod: "POST", // 请求方法 reqTimeout: 30, // 请求超时时间,默认60s headers: { // 自定义 header }, // proxy: "http://127.0.0.1:8899" // http请求代理 }, }, }) // 通过client对象调用想要访问的接口(Action),需要传入请求对象(Params)以及响应回调函数 // 即:client.Action(Params).then(res => console.log(res), err => console.error(err)) // 如:查询云服务器可用区列表 client.DescribeZones().then( (data) => { console.log(data) }, (err) => { console.error("error", err) } ) ``` -------------------------------- ### CVM - Describe Zones Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Example of how to query available zones for a specific region using the CVM service client, demonstrating both Promise-based and async/await usage. ```APIDOC ## CVM - Describe Zones Query available zones for a specific region using the CVM service client. ```typescript import { cvm } from "tencentcloud-sdk-nodejs-cvm" const CvmClient = cvm.v20170312.Client const client = new CvmClient({ credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, }, region: "ap-shanghai", }) // Using Promise client.DescribeZones().then( (data) => { console.log("Available zones:", data.ZoneSet) // Output: [{ Zone: "ap-shanghai-1", ZoneName: "Shanghai Zone 1", ... }, ...] }, (err) => { console.error("Error:", err.message) console.error("RequestId:", err.requestId) } ) // Using async/await async function listZones() { try { const result = await client.DescribeZones() for (const zone of result.ZoneSet) { console.log(`${zone.Zone}: ${zone.ZoneName} (${zone.ZoneState})`) } } catch (err) { console.error("Failed to list zones:", err) } } ``` ``` -------------------------------- ### CVM - Instance Lifecycle Operations Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Start, stop, reboot, and terminate CVM instances. ```APIDOC ## CVM - Instance Lifecycle Operations ### Description Start, stop, reboot, and terminate CVM instances. ### Method POST ### Endpoint - Stop Instances: `/cvm/v20170312/StopInstances` - Start Instances: `/cvm/v20170312/StartInstances` - Reboot Instances: `/cvm/v20170312/RebootInstances` - Terminate Instances: `/cvm/v20170312/TerminateInstances` ### Parameters #### Common Parameters (for all operations) - **InstanceIds** (array of strings) - Required - The IDs of the instances to operate on. #### StopInstances Specific Parameters - **StopType** (string) - Optional - The type of shutdown. "SOFT" for graceful shutdown, "HARD" for force shutdown. - **StoppedMode** (string) - Optional - Specifies whether to stop billing when the instance is stopped (e.g., "STOP_CHARGING"). #### RebootInstances Specific Parameters - **ForceReboot** (boolean) - Optional - Set to `true` for a force reboot. ### Request Example (Stop Instances) ```json { "InstanceIds": ["ins-xxxxxxxx"], "StopType": "SOFT", "StoppedMode": "STOP_CHARGING" } ``` ### Request Example (Start Instances) ```json { "InstanceIds": ["ins-xxxxxxxx"] } ``` ### Request Example (Reboot Instances) ```json { "InstanceIds": ["ins-xxxxxxxx"], "ForceReboot": false } ``` ### Request Example (Terminate Instances) ```json { "InstanceIds": ["ins-xxxxxxxx"] } ``` ### Response (for all operations) #### Success Response (200) - **RequestId** (string) - The request ID. #### Response Example ```json { "RequestId": "a1b2c3d4-e5f6-7890-1234-567890abcdef" } ``` ``` -------------------------------- ### Initialize Speech Oral Evaluation Session with SOE Service Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt This TypeScript example demonstrates how to initialize a session for the Smart Oral Evaluation (SOE) service. Configure the client with your credentials, region, and desired profile settings. The `InitOralProcess` method requires parameters like `SessionId`, `RefText`, `WorkMode`, `EvalMode`, and `ScoreCoeff`. ```typescript import { soe } from "tencentcloud-sdk-nodejs-soe" const SoeClient = soe.v20180724.Client const client = new SoeClient({ credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, }, region: "ap-shanghai", profile: { signMethod: "HmacSHA256", httpProfile: { reqMethod: "POST", reqTimeout: 30, }, }, }) // Initialize oral evaluation session client.InitOralProcess({ SessionId: "session_" + Date.now(), RefText: "hello world", WorkMode: 0, // 0: stream mode, 1: one-time mode EvalMode: 1, // 1: word mode, 2: sentence mode ScoreCoeff: 3.5, // Score coefficient }).then( (response) => { console.log("Session initialized:", response) }, (err) => { console.error("Error:", err) } ) ``` -------------------------------- ### Using CvmRoleCredential for Authentication Source: https://github.com/tencentcloud/tencentcloud-sdk-nodejs/blob/master/README.md Example demonstrating how to use CvmRoleCredential for authentication, which leverages Tencent Cloud instance roles for obtaining temporary credentials. This is a more secure alternative to hardcoding SecretId and SecretKey. ```javascript // ... const CvmRoleCredential = require("tencentcloud-sdk-nodejs/tencentcloud/common/cvm_role_credential").default new XxxClient({ // ... credential: new CvmRoleCredential(), // ... }) ``` -------------------------------- ### Query CBS Disks Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Query Cloud Block Storage disks using the CBS service client. This example demonstrates how to initialize the client and use a callback style for the query. ```typescript import { cbs } from "tencentcloud-sdk-nodejs-cbs" const CbsClient = cbs.v20170312.Client const client = new CbsClient({ credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, }, region: "ap-shanghai", }) // Using callback style client.DescribeDisks({}, function (err, response) { if (err) { console.log("Error:", err) return } console.log("Total disks:", response.TotalCount) for (const disk of response.DiskSet) { console.log(`Disk ID: ${disk.DiskId}`) console.log(`Name: ${disk.DiskName}`) console.log(`Size: ${disk.DiskSize} GB`) console.log(`Type: ${disk.DiskType}`) console.log(`State: ${disk.DiskState}`) console.log("---") } }) ``` -------------------------------- ### Manage CVM Instance Lifecycle Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Perform lifecycle operations on CVM instances such as stopping, starting, rebooting, and terminating. This requires an initialized client and a list of instance IDs. ```typescript import { cvm } from "tencentcloud-sdk-nodejs-cvm" const CvmClient = cvm.v20170312.Client const client = new CvmClient({ credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, }, region: "ap-shanghai", }) const instanceIds = ["ins-xxxxxxxx"] // Stop instances async function stopInstances() { const result = await client.StopInstances({ InstanceIds: instanceIds, StopType: "SOFT", // SOFT: graceful shutdown, HARD: force shutdown StoppedMode: "STOP_CHARGING", // Stop billing when stopped }) console.log("Stop requested, RequestId:", result.RequestId) } // Start instances async function startInstances() { const result = await client.StartInstances({ InstanceIds: instanceIds, }) console.log("Start requested, RequestId:", result.RequestId) } // Reboot instances async function rebootInstances() { const result = await client.RebootInstances({ InstanceIds: instanceIds, ForceReboot: false, // Set true for force reboot }) console.log("Reboot requested, RequestId:", result.RequestId) } // Terminate instances async function terminateInstances() { const result = await client.TerminateInstances({ InstanceIds: instanceIds, }) console.log("Termination requested, RequestId:", result.RequestId) } ``` -------------------------------- ### Modify SDK Import Statement Source: https://github.com/tencentcloud/tencentcloud-sdk-nodejs/blob/master/README.md After installing a specific product SDK, update your import statements to reference the product module directly instead of the general tencentcloud module. ```diff - const tencentcloud = require("tencentcloud-sdk-nodejs") + const { cvm } = require("tencentcloud-sdk-nodejs-cvm") - const CvmClient = tencentcloud.cvm.v20170312.Client + const CvmClient = cvm.v20170312.Client ``` -------------------------------- ### Upload Logs to CLS with Protobuf and LZ4 Compression Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Use this snippet to upload logs to Cloud Log Service (CLS) using protobuf encoding and LZ4 compression. Ensure you have the 'tencentcloud-sdk-nodejs-common', 'protobufjs', and 'lz4' packages installed. Configure your CLS topic ID and credentials. ```javascript const { CommonClient } = require("tencentcloud-sdk-nodejs-common") const protobuf = require("protobufjs") const lz4 = require("lz4") const path = require("path") const client = new CommonClient( "cls.tencentcloudapi.com", "2020-10-16", { credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, }, region: "ap-guangzhou", profile: { httpProfile: { endpoint: "cls.tencentcloudapi.com", headers: { "X-CLS-TopicId": "your-topic-id", "X-CLS-CompressType": "lz4", }, }, }, } ) // Compress data with LZ4 function compress(input) { const output = Buffer.alloc(lz4.encodeBound(input.length)) const compressedSize = lz4.encodeBlock(input, output) return output.slice(0, compressedSize) } // Build protobuf log payload function buildLogPayload() { const root = protobuf.loadSync(path.join(__dirname, "cls.proto")) const LogGroupList = root.lookupType("cls.LogGroupList") const payload = { logGroupList: [ { logs: [ { time: Date.now(), contents: [ { key: "level", value: "INFO" }, { key: "message", value: "User logged in" }, { key: "user_id", value: "12345" }, ], }, ], }, ], } return LogGroupList.encode(payload).finish() } // Upload logs const compressedData = compress(buildLogPayload()) client.requestOctetStream("UploadLog", compressedData).then( (data) => console.log("Log uploaded:", data), (err) => console.error("Upload failed:", err) ) ``` -------------------------------- ### Hunyuan AI Chat Completions (Streaming) Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Utilize the Hunyuan AI service for streaming chat completions using Server-Sent Events (SSE). This example shows how to handle messages as they arrive. ```typescript import { hunyuan } from "tencentcloud-sdk-nodejs-hunyuan" import { SSEResponseModel } from "tencentcloud-sdk-nodejs-common/tencentcloud/common/sse_response_model" const HunyuanClient = hunyuan.v20230901.Client const client = new HunyuanClient({ credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, }, region: "ap-guangzhou", profile: { httpProfile: { endpoint: "hunyuan.tencentcloudapi.com", }, }, }) // Streaming chat completion client.ChatCompletions({ Model: "hunyuan-pro", Messages: [ { Role: "user", Content: "Tell me a short joke", }, ], Stream: true, // Enable streaming }).then( async (res) => { const stream = res as SSEResponseModel // Method 1: Event-based streaming stream.on("message", (message) => { if (message.data) { const data = JSON.parse(message.data) for (const choice of data.Choices || []) { if (choice.Delta?.Content) { process.stdout.write(choice.Delta.Content) } } } }) stream.on("close", () => { console.log("\n[Stream completed]") }) stream.on("error", (err) => { console.error("Stream error:", err) }) // Method 2: Async iterator (alternative) // for await (const message of stream) { // if (message.data) { // const data = JSON.parse(message.data) // process.stdout.write(data.Choices?.[0]?.Delta?.Content || "") // } // } }, (err) => { console.error("Error:", err) } ) ``` -------------------------------- ### Hunyuan AI Chat Completions (Non-Streaming) Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Perform non-streaming chat completions using the Hunyuan AI service. This example demonstrates a basic request and response handling. ```typescript import { hunyuan } from "tencentcloud-sdk-nodejs-hunyuan" const HunyuanClient = hunyuan.v20230901.Client const client = new HunyuanClient({ credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, }, region: "ap-guangzhou", }) // Non-streaming chat completion client.ChatCompletions({ Model: "hunyuan-pro", Messages: [ { Role: "system", Content: "You are a helpful assistant.", }, { Role: "user", Content: "What is the capital of France?", }, ], Stream: false, // Disable streaming }).then( (res) => { console.log("Response:", res.Choices[0].Message.Content) console.log("Usage:", res.Usage) // Output: { PromptTokens: X, CompletionTokens: Y, TotalTokens: Z } }, (err) => { console.error("Error:", err) } ) ``` -------------------------------- ### CVM - Run Instances Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Create new CVM instances with detailed configuration. ```APIDOC ## CVM - Run Instances ### Description Create new CVM instances with detailed configuration. ### Method POST ### Endpoint /cvm/v20170312/RunInstances ### Parameters #### Request Body - **InstanceChargeType** (string) - Required - The billing method for the instance (e.g., "POSTPAID_BY_HOUR"). - **Placement** (object) - Required - Specifies the placement of the instance. - **Zone** (string) - Required - The availability zone for the instance. - **InstanceType** (string) - Required - The instance type (e.g., "S5.MEDIUM2"). - **ImageId** (string) - Required - The ID of the image to use for the instance. - **SystemDisk** (object) - Required - Configuration for the system disk. - **DiskType** (string) - Required - The type of the system disk (e.g., "CLOUD_PREMIUM"). - **DiskSize** (integer) - Required - The size of the system disk in GB. - **InternetAccessible** (object) - Optional - Configuration for network access. - **InternetChargeType** (string) - Optional - The billing method for internet access (e.g., "TRAFFIC_POSTPAID_BY_HOUR"). - **InternetMaxBandwidthOut** (integer) - Optional - The maximum outbound bandwidth in Mbps. - **PublicIpAssigned** (boolean) - Optional - Whether to assign a public IP address. - **InstanceCount** (integer) - Optional - The number of instances to create (default is 1). - **InstanceName** (string) - Optional - The name of the instance. - **LoginSettings** (object) - Optional - Login configuration for the instance. - **KeyIds** (array of strings) - Optional - SSH key pair IDs for login. - **SecurityGroupIds** (array of strings) - Optional - IDs of security groups to associate with the instance. - **TagSpecification** (array) - Optional - Tags to apply to the instance. - **ResourceType** (string) - Required - The resource type (e.g., "instance"). - **Tags** (array) - Required - A list of tags. - **Key** (string) - Required - The tag key. - **Value** (string) - Required - The tag value. ### Request Example ```json { "InstanceChargeType": "POSTPAID_BY_HOUR", "Placement": { "Zone": "ap-shanghai-2" }, "InstanceType": "S5.MEDIUM2", "ImageId": "img-eb30mz89", "SystemDisk": { "DiskType": "CLOUD_PREMIUM", "DiskSize": 50 }, "InternetAccessible": { "InternetChargeType": "TRAFFIC_POSTPAID_BY_HOUR", "InternetMaxBandwidthOut": 10, "PublicIpAssigned": true }, "InstanceCount": 1, "InstanceName": "my-test-instance", "LoginSettings": { "KeyIds": ["skey-xxxxxxxx"] }, "SecurityGroupIds": ["sg-xxxxxxxx"], "TagSpecification": [ { "ResourceType": "instance", "Tags": [ { "Key": "Environment", "Value": "Development" } ] } ] } ``` ### Response #### Success Response (200) - **InstanceIdSet** (array of strings) - A list of IDs for the created instances. - **RequestId** (string) - The request ID. #### Response Example ```json { "InstanceIdSet": ["ins-abcdefgh"], "RequestId": "a1b2c3d4-e5f6-7890-1234-567890abcdef" } ``` ``` -------------------------------- ### Create CVM Instances Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Use this to create new CVM instances with detailed configurations including instance type, image, disk, and network settings. Ensure the SDK is imported and a client is initialized. ```typescript import { cvm } from "tencentcloud-sdk-nodejs-cvm" const CvmClient = cvm.v20170312.Client const client = new CvmClient({ credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, }, region: "ap-shanghai", }) // Create a new instance client.RunInstances({ InstanceChargeType: "POSTPAID_BY_HOUR", Placement: { Zone: "ap-shanghai-2", }, InstanceType: "S5.MEDIUM2", // 2 vCPU, 2GB RAM ImageId: "img-eb30mz89", // Ubuntu Server 20.04 SystemDisk: { DiskType: "CLOUD_PREMIUM", DiskSize: 50, // 50 GB }, InternetAccessible: { InternetChargeType: "TRAFFIC_POSTPAID_BY_HOUR", InternetMaxBandwidthOut: 10, // 10 Mbps PublicIpAssigned: true, }, InstanceCount: 1, InstanceName: "my-test-instance", LoginSettings: { KeyIds: ["skey-xxxxxxxx"], // SSH key pair ID }, SecurityGroupIds: ["sg-xxxxxxxx"], TagSpecification: [ { ResourceType: "instance", Tags: [ { Key: "Environment", Value: "Development" }, ], }, ], }).then( (data) => { console.log("Instance created successfully!") console.log("Instance IDs:", data.InstanceIdSet) console.log("RequestId:", data.RequestId) }, (err) => { console.error("Failed to create instance:", err.message) } ) ``` -------------------------------- ### Import and Use Full SDK Package (JavaScript) Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Import the entire Tencent Cloud SDK for Node.js package to access all available product clients. Ensure credentials and region are configured. ```javascript const tencentcloud = require("tencentcloud-sdk-nodejs") // Access product clients from the full SDK const CvmClient = tencentcloud.cvm.v20170312.Client const VpcClient = tencentcloud.vpc.v20170312.Client const ClsClient = tencentcloud.cls.v20201016.Client const cvmClient = new CvmClient({ credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, }, region: "ap-shanghai", }) cvmClient.DescribeZones().then( (data) => console.log(data), (err) => console.error(err) ) ``` -------------------------------- ### Pack SDK to .tgz Source: https://github.com/tencentcloud/tencentcloud-sdk-nodejs/blob/master/README.md Package the built SDK into an NPM compressed file (e.g., tencentcloud-sdk-nodejs-4.0.0.tgz). ```bash npm pack ``` -------------------------------- ### Clone SDK from Git Source: https://github.com/tencentcloud/tencentcloud-sdk-nodejs/blob/master/README.md Clone the Node.js SDK source code from a Git repository. ```bash git clone https://cnb.cool/tencent/cloud/api/sdk/tencentcloud-sdk-nodejs # 或者 git clone https://github.com/tencentcloud/tencentcloud-sdk-nodejs # 或者 git clone https://gitee.com/tencentcloud/tencentcloud-sdk-nodejs ``` -------------------------------- ### Configure HTTP Proxy for SDK Clients Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Configure HTTP proxy settings for SDK clients when operating in environments behind firewalls. Supports both proxy strings and custom agent configurations. ```typescript import { cvm } from "tencentcloud-sdk-nodejs-cvm" import { HttpsProxyAgent } from "https-proxy-agent" const CvmClient = cvm.v20170312.Client // Method 1: Using proxy string const client1 = new CvmClient({ credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, }, region: "ap-shanghai", profile: { httpProfile: { proxy: "http://127.0.0.1:8899", }, }, }) // Method 2: Using custom agent (higher priority) const client2 = new CvmClient({ credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, }, region: "ap-shanghai", profile: { httpProfile: { agent: new HttpsProxyAgent("http://127.0.0.1:8899"), }, }, }) // Method 3: Using environment variable // Set http_proxy=http://127.0.0.1:8899 before running ``` -------------------------------- ### Import and Use Full SDK Package (TypeScript) Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Import the full Tencent Cloud SDK for Node.js with TypeScript support for type-safe client access and request/response handling. Demonstrates calling an API and processing results. ```typescript import * as tencentcloud from "tencentcloud-sdk-nodejs" // Access product clients with full type support const CvmClient = tencentcloud.cvm.v20170312.Client const client = new CvmClient({ credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, }, region: "ap-shanghai", }) // Full TypeScript type inference for requests and responses async function main() { const result = await client.DescribeInstances({ Limit: 10, Offset: 0, }) // result is fully typed as DescribeInstancesResponse console.log("Total:", result.TotalCount) for (const instance of result.InstanceSet || []) { console.log(instance.InstanceId, instance.InstanceName) } } main() ``` -------------------------------- ### CVM - Describe Instances Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Query CVM instances with filters for zone and billing type. ```APIDOC ## CVM - Describe Instances ### Description Query CVM instances with filters for zone and billing type. ### Method POST ### Endpoint /cvm/v20170312/DescribeInstances ### Parameters #### Query Parameters - **Offset** (integer) - Optional - Offset for pagination. - **Limit** (integer) - Optional - Limit for pagination. #### Request Body - **Filters** (array) - Optional - Filter conditions for querying instances. - **Name** (string) - Required - The name of the filter field. - **Values** (array of strings) - Required - The value of the filter field. ### Request Example ```json { "Filters": [ { "Name": "zone", "Values": ["ap-shanghai-1", "ap-shanghai-2"] }, { "Name": "instance-charge-type", "Values": ["POSTPAID_BY_HOUR"] } ], "Offset": 0, "Limit": 20 } ``` ### Response #### Success Response (200) - **TotalCount** (integer) - The total number of instances matching the filters. - **InstanceSet** (array) - A list of CVM instances. - **InstanceId** (string) - The ID of the instance. - **InstanceName** (string) - The name of the instance. - **InstanceState** (string) - The state of the instance. - **InstanceType** (string) - The type of the instance. - **PrivateIpAddresses** (array of strings) - The private IP addresses of the instance. - **PublicIpAddresses** (array of strings) - The public IP addresses of the instance. #### Response Example ```json { "TotalCount": 1, "InstanceSet": [ { "InstanceId": "ins-abcdefgh", "InstanceName": "my-instance", "InstanceState": "RUNNING", "InstanceType": "S5.MEDIUM2", "PrivateIpAddresses": ["10.0.0.1"], "PublicIpAddresses": ["203.0.113.1"] } ], "RequestId": "a1b2c3d4-e5f6-7890-1234-567890abcdef" } ``` ``` -------------------------------- ### Configure CVM Client with Full Options Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Configure a CVM client with comprehensive authentication and advanced settings, including signature method, language, request details, and proxy. ```typescript import { cvm } from "tencentcloud-sdk-nodejs-cvm" const CvmClient = cvm.v20170312.Client // Full configuration example const client = new CvmClient({ // Required: Authentication credentials credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, // Optional: For temporary credentials (STS) token: process.env.TENCENTCLOUD_TOKEN, }, // Required for regional services, optional for global services region: "ap-shanghai", // Optional: Advanced configuration profile: { signMethod: "TC3-HMAC-SHA256", // Signature method language: "en-US", // API response language: "zh-CN" | "en-US" httpProfile: { reqMethod: "POST", // HTTP method: "POST" | "GET" reqTimeout: 60, // Request timeout in seconds endpoint: "cvm.tencentcloudapi.com", // Custom endpoint protocol: "https://", // Protocol proxy: "http://127.0.0.1:8899", // HTTP proxy headers: { "X-TC-TraceId": "custom-trace-id", // Custom headers }, }, }, }) ``` -------------------------------- ### Query CVM Instances with Filters Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Use this to query CVM instances based on specific filters like zone and billing type. Ensure the SDK is imported and a client is initialized with credentials and region. ```typescript import { cvm } from "tencentcloud-sdk-nodejs-cvm" const CvmClient = cvm.v20170312.Client const client = new CvmClient({ credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, }, region: "ap-shanghai", }) // Query instances with filters client.DescribeInstances({ Filters: [ { Name: "zone", Values: ["ap-shanghai-1", "ap-shanghai-2"], }, { Name: "instance-charge-type", Values: ["POSTPAID_BY_HOUR"], // Pay-as-you-go instances }, ], Offset: 0, Limit: 20, }).then( (data) => { console.log("Total instances:", data.TotalCount) for (const instance of data.InstanceSet) { console.log(`ID: ${instance.InstanceId}`) console.log(`Name: ${instance.InstanceName}`) console.log(`State: ${instance.InstanceState}`) console.log(`Type: ${instance.InstanceType}`) console.log(`Private IP: ${instance.PrivateIpAddresses?.join(", ")}`) console.log(`Public IP: ${instance.PublicIpAddresses?.join(", ")}`) console.log("---") } }, (err) => { console.error("Error:", err) } ) ``` -------------------------------- ### Configure HTTP Proxy via Environment Variable Source: https://github.com/tencentcloud/tencentcloud-sdk-nodejs/blob/master/README.md Set the http_proxy environment variable to configure an HTTP proxy for SDK requests. This is necessary when operating in an environment that requires a proxy to access external resources. ```sh # MacOS http_proxy=http://代理地址:代理端口 node app.js ``` -------------------------------- ### CBS - Describe Disks Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Query Cloud Block Storage disks using the CBS service client. ```APIDOC ## CBS - Describe Disks ### Description Query Cloud Block Storage disks using the CBS service client. ### Method POST ### Endpoint /cbs/v20170312/DescribeDisks ### Parameters #### Request Body (No specific parameters are shown in the example, implying an empty object can be used to query all disks. Specific filters might be available but are not detailed in the provided text.) ### Request Example ```json {} ``` ### Response #### Success Response (200) - **TotalCount** (integer) - The total number of disks matching the query. - **DiskSet** (array) - A list of CBS disks. - **DiskId** (string) - The ID of the disk. - **DiskName** (string) - The name of the disk. - **DiskSize** (integer) - The size of the disk in GB. - **DiskType** (string) - The type of the disk. - **DiskState** (string) - The state of the disk. #### Response Example ```json { "TotalCount": 1, "DiskSet": [ { "DiskId": "disk-abcdefgh", "DiskName": "my-data-disk", "DiskSize": 100, "DiskType": "CLOUD_PREMIUM", "DiskState": "ATTACHED" } ], "RequestId": "a1b2c3d4-e5f6-7890-1234-567890abcdef" } ``` ``` -------------------------------- ### Query CVM Available Zones using Async/Await Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Retrieve a list of available zones for a specific region using the CVM service client with async/await syntax. This approach simplifies asynchronous code handling. ```typescript import { cvm } from "tencentcloud-sdk-nodejs-cvm" const CvmClient = cvm.v20170312.Client const client = new CvmClient({ credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, }, region: "ap-shanghai", }) // Using async/await async function listZones() { try { const result = await client.DescribeZones() for (const zone of result.ZoneSet) { console.log(`${zone.Zone}: ${zone.ZoneName} (${zone.ZoneState})`) } } catch (err) { console.error("Failed to list zones:", err) } } ``` -------------------------------- ### Query CVM Available Zones using Promise Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Retrieve a list of available zones for a specific region using the CVM service client with a Promise-based approach. Ensure credentials and region are configured. ```typescript import { cvm } from "tencentcloud-sdk-nodejs-cvm" const CvmClient = cvm.v20170312.Client const client = new CvmClient({ credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, }, region: "ap-shanghai", }) // Using Promise client.DescribeZones().then( (data) => { console.log("Available zones:", data.ZoneSet) // Output: [{ Zone: "ap-shanghai-1", ZoneName: "Shanghai Zone 1", ... }, ...] }, (err) => { console.error("Error:", err.message) console.error("RequestId:", err.requestId) } ) ``` -------------------------------- ### Make API Calls with CommonClient Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Use CommonClient to make API calls to any Tencent Cloud service without product-specific SDKs. Ensure your environment variables TENCENTCLOUD_SECRET_ID and TENCENTCLOUD_SECRET_KEY are set. ```typescript import { CommonClient } from "tencentcloud-sdk-nodejs-common" // Create a common client for CVM service const client = new CommonClient( "cvm.tencentcloudapi.com", // Service endpoint "2017-03-12", // API version { credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, }, region: "ap-shanghai", profile: { httpProfile: { endpoint: "cvm.tencentcloudapi.com", }, }, } ) // Make API request by action name const params = { Filters: [ { Name: "zone", Values: ["ap-shanghai-1"], }, ], Limit: 10, } client.request("DescribeInstances", params).then( (data) => { console.log("Instances:", data) }, (err) => { console.error("Error:", err) } ) // Example: Call VPC API const vpcClient = new CommonClient( "vpc.tencentcloudapi.com", "2017-03-12", { credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, }, region: "ap-shanghai", } ) vpcClient.request("DescribeVpcs", { Limit: 10 }).then( (data) => console.log("VPCs:", data), (err) => console.error("Error:", err) ) ``` -------------------------------- ### Handle Tencent Cloud SDK HTTP Exceptions Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt This TypeScript code demonstrates how to catch and handle `TencentCloudSDKHttpException` errors. It shows how to access detailed error information like `message`, `code`, `requestId`, `traceId`, and `httpCode`, and provides a switch case for handling specific error codes. ```typescript import { cvm } from "tencentcloud-sdk-nodejs-cvm" import TencentCloudSDKHttpException from "tencentcloud-sdk-nodejs-common/tencentcloud/common/exception/tencent_cloud_sdk_exception" const CvmClient = cvm.v20170312.Client const client = new CvmClient({ credential: { secretId: process.env.TENCENTCLOUD_SECRET_ID, secretKey: process.env.TENCENTCLOUD_SECRET_KEY, }, region: "ap-shanghai", }) async function handleErrors() { try { await client.DescribeInstances({ InstanceIds: ["ins-invalid-id"], }) } catch (err) { if (err instanceof TencentCloudSDKHttpException) { console.error("Error Message:", err.message) console.error("Error Code:", err.code) console.error("Request ID:", err.requestId) console.error("Trace ID:", err.traceId) console.error("HTTP Code:", err.httpCode) // Handle specific error codes switch (err.code) { case "AuthFailure.SecretIdNotFound": console.error("Invalid SecretId") break case "InvalidParameterValue.InvalidInstanceId": console.error("Invalid instance ID format") break case "ResourceNotFound.NoSuchInstance": console.error("Instance not found") break default: console.error("Unknown error") } } else { console.error("Unexpected error:", err) } } } handleErrors() ``` -------------------------------- ### Enable HTTP Debug Logging Source: https://github.com/tencentcloud/tencentcloud-sdk-nodejs/blob/master/README.md Set the NODE_DEBUG environment variable to 'http' to enable detailed HTTP request logging, which is useful for troubleshooting network connectivity issues. ```sh # MacOS NODE_DEBUG=http node app.js # windows cmd set NODE_DEBUG=http & node app.js # windows powershell $env:NODE_DEBUG='http' ; node app.js ``` -------------------------------- ### Authenticate with CVM Instance Role Credentials Source: https://context7.com/tencentcloud/tencentcloud-sdk-nodejs/llms.txt Use this TypeScript snippet to authenticate with Tencent Cloud services using instance role credentials when running on CVM instances. This avoids hardcoding sensitive credentials. The SDK automatically fetches temporary credentials from instance metadata. ```typescript import { cvm } from "tencentcloud-sdk-nodejs-cvm" import CvmRoleCredential from "tencentcloud-sdk-nodejs-common/tencentcloud/common/cvm_role_credential" const CvmClient = cvm.v20170312.Client // Create client using CVM instance role (no hardcoded credentials) const client = new CvmClient({ credential: new CvmRoleCredential(), region: "ap-shanghai", }) // The SDK automatically fetches temporary credentials from instance metadata client.DescribeZones().then( (data) => { console.log("Zones:", data.ZoneSet) }, (err) => { console.error("Error:", err) } ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.