### Complete Configuration Management Example Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/configuration.md Demonstrates creating, checking, merging, getting, and modifying configuration values. Also shows how to create derived configurations. ```typescript import { Configuration, ClientOptionKeys } from 'nacos'; function main() { // Create base configuration const baseConfig = new Configuration({ requestTimeout: 5000, refreshInterval: 30000, }); // Check for configuration if (baseConfig.has(ClientOptionKeys.REQUEST_TIMEOUT)) { console.log('Timeout configured'); } // Merge in new values baseConfig.merge({ serverAddr: '127.0.0.1:8848', namespace: 'production', }); // Get individual values const namespace = baseConfig.get(ClientOptionKeys.NAMESPACE); console.log('Namespace:', namespace); // 'production' // Get all configuration const allConfig = baseConfig.get(); console.log('All config:', allConfig); // Modify values baseConfig.modify(ClientOptionKeys.ENDPOINT, (ep) => { return ep ? ep + ':8080' : 'localhost:8080'; }); // Create derived configuration const prodConfig = baseConfig.attach({ ssl: true, appName: 'prod-app', }); // Create derived configuration const devConfig = new Configuration({ serverAddr: 'localhost:8848', }) .set(ClientOptionKeys.NAMESPACE, 'development') .set(ClientOptionKeys.REQUEST_TIMEOUT, 3000) .set(ClientOptionKeys.SSL, false); console.log('Dev timeout:', devConfig.get(ClientOptionKeys.REQUEST_TIMEOUT)); } main(); ``` -------------------------------- ### Nacos Configuration Service Quick Start Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/README.md Demonstrates how to create a NacosConfigClient, get configuration, subscribe to changes, and publish configuration. Ensure the Nacos server is running at the specified address. ```typescript import { NacosConfigClient } from 'nacos'; // Create client const client = new NacosConfigClient({ serverAddr: '127.0.0.1:8848', namespace: 'production', }); // Wait for ready await client.ready(); // Get configuration const config = await client.getConfig('app.properties', 'DEFAULT_GROUP'); // Subscribe to changes client.subscribe( { dataId: 'app.properties', group: 'DEFAULT_GROUP' }, (content) => { console.log('Config updated:', content); } ); // Publish configuration await client.publishSingle('app.properties', 'DEFAULT_GROUP', 'key=value'); ``` -------------------------------- ### Method Chaining for Configuration Setup Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/configuration.md Illustrates setting multiple configuration options using method chaining for a more concise setup. Useful for initializing configuration with several parameters. ```typescript const config = new Configuration() .set(ClientOptionKeys.SERVER_PORT, 8848) .set(ClientOptionKeys.NAMESPACE, 'production') .set(ClientOptionKeys.REQUEST_TIMEOUT, 5000) .set(ClientOptionKeys.SSL, true) .set(ClientOptionKeys.APPNAME, 'my-app') .modify(ClientOptionKeys.ENDPOINT, (ep) => { const [host, port] = ep.split(':'); return host + ':' + (port || '8080'); }); console.log('Configuration ready:', config.get()); ``` -------------------------------- ### Nacos Server List Manager Example Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/server-list-manager.md Demonstrates setting up and using the ServerListManager in both lookup and direct modes. Includes fetching unit lists, getting current server addresses, updating server selection, and cleaning up resources. Ensure Nacos server is running for direct mode. ```typescript import { ServerListManager } from 'nacos'; import { Configuration } from 'nacos'; async function main() { // Setup for lookup mode const lookupConfig = new Configuration({ endpoint: 'acm.aliyun.com:8080', serverPort: 8080, refreshInterval: 30000, }); const lookupManager = new ServerListManager({ configuration: lookupConfig, }); await lookupManager.ready(); const units = await lookupManager.fetchUnitLists(); console.log('Available units:', units); const addr = await lookupManager.getCurrentServerAddr(); console.log('Current server:', addr); // Setup for direct mode const directConfig = new Configuration({ serverAddr: ['127.0.0.1:8848', '127.0.0.1:8849'], }); const directManager = new ServerListManager({ configuration: directConfig, }); await directManager.ready(); const directAddr = await directManager.getCurrentServerAddr(); console.log('Direct mode server:', directAddr); // Update server selection await directManager.updateCurrentServer(); const newAddr = await directManager.getCurrentServerAddr(); console.log('New server (round-robin):', newAddr); // Cleanup lookupManager.close(); directManager.close(); } main().catch(console.error); ``` -------------------------------- ### Nacos Configuration Service with Node.js Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/README.md Provides examples for initializing NacosConfigClient in both find address and direct modes. It covers getting, subscribing to, publishing, and removing configuration. ```javascript import {NacosConfigClient} from 'nacos'; // ts const NacosConfigClient = require('nacos').NacosConfigClient; // js // for find address mode const configClient = new NacosConfigClient({ endpoint: 'acm.aliyun.com', namespace: '***************', accessKey: '***************', secretKey: '***************', requestTimeout: 6000, }); // for direct mode const configClient = new NacosConfigClient({ serverAddr: '127.0.0.1:8848', }); // get config once const content= await configClient.getConfig('test', 'DEFAULT_GROUP'); console.log('getConfig = ',content); // listen data changed configClient.subscribe({ dataId: 'test', group: 'DEFAULT_GROUP', }, content => { console.log(content); }); // publish config const content= await configClient.publishSingle('test', 'DEFAULT_GROUP', '测试'); console.log('getConfig = ',content); // remove config await configClient.remove('test', 'DEFAULT_GROUP'); ``` -------------------------------- ### GET Request Example Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/http-agent.md Use this to retrieve configuration details from Nacos. Ensure the API path and query parameters are correctly specified. ```typescript // Example: Retrieve configuration GET /v1/cs/configs?dataId=app&group=DEFAULT_GROUP ``` -------------------------------- ### GET Requests Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/http-agent.md Handles GET requests, typically used for retrieving configuration data. Includes an example of retrieving a specific configuration. ```APIDOC ## GET /v1/cs/configs ### Description Retrieve configuration data. ### Method GET ### Endpoint /v1/cs/configs ### Query Parameters - **dataId** (string) - Required - The ID of the configuration data. - **group** (string) - Required - The group the configuration belongs to. ### Request Example ``` GET /v1/cs/configs?dataId=app&group=DEFAULT_GROUP ``` ``` -------------------------------- ### Complete ClientWorker Example Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/client-worker.md This example demonstrates how to set up and use the ClientWorker to subscribe to configuration changes, retrieve current configurations, and publish new configurations. Ensure Nacos server is running and accessible at the specified address. ```typescript import { ClientWorker } from 'nacos'; import { Configuration } from 'nacos'; import { ServerListManager } from 'nacos'; import { HttpAgent } from 'nacos'; async function main() { // Setup configuration const config = new Configuration({ serverAddr: '127.0.0.1:8848', namespace: 'production', }); // Create worker const worker = new ClientWorker({ configuration: config, httpAgent: new HttpAgent({ configuration: config }), }); await worker.ready(); // Subscribe to config changes worker.subscribe( { dataId: 'database', group: 'DEFAULT_GROUP' }, (content) => { console.log('Database config changed:', content); } ); // Get config const dbConfig = await worker.getConfig('database', 'DEFAULT_GROUP'); console.log('Current database config:', dbConfig); // Publish new config await worker.publishSingle( 'database', 'DEFAULT_GROUP', 'host=db.example.com\nport=5432' ); // Cleanup worker.close(); } main().catch(console.error); ``` -------------------------------- ### RoleArn AssumeRole Credential Provider Example Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/packages/nacos/README.md Example of creating a credential provider using `createRoleArnProvider` for assuming an Aliyun RAM role. It includes logic for caching credentials and handling expiration. ```javascript const clientOptions = { serverAddr: '127.0.0.1:8848', aliyunCredentialsProvider: createRoleArnProvider({ accessKeyId: 'AccessKeyId', accessKeySecret: 'AccessKeySecret', securityToken: 'OptionalSecurityToken', roleArn: 'acs:ram::123456789012****:role/example-role', roleSessionName: 'nacos-nodejs-sdk', policy: '{"Version":"1","Statement":[]}', roleSessionExpiration: 3600, }), }; function createRoleArnProvider(options) { let cachedCredentials; return async () => { if (cachedCredentials && Date.parse(cachedCredentials.Expiration) - Date.now() > 3 * 60 * 1000) { return cachedCredentials; } // Call Aliyun STS AssumeRole with options.roleArn, options.roleSessionName, // options.policy, options.roleSessionExpiration, and the source AK/SK. cachedCredentials = await assumeRoleByAliyunSdk(options); return { AccessKeyId: cachedCredentials.AccessKeyId, AccessKeySecret: cachedCredentials.AccessKeySecret, SecurityToken: cachedCredentials.SecurityToken, Expiration: cachedCredentials.Expiration, }; }; } ``` -------------------------------- ### Install Nacos Node.js SDK Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/README.md Install the Nacos Node.js SDK using npm. ```bash npm install nacos --save ``` -------------------------------- ### Get All Configurations Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/nacos-config-client.md Retrieve all configuration strings within the current tenant or namespace. This is an asynchronous operation. ```typescript const configs = await configClient.getConfigs(); console.log('All configs:', configs); ``` -------------------------------- ### RoleArn AssumeRole Provider Example Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/README.md Example of creating a credentials provider for RoleArn assumption using Aliyun STS. It includes caching and expiration logic. ```javascript const clientOptions = { serverAddr: '127.0.0.1:8848', aliyunCredentialsProvider: createRoleArnProvider({ accessKeyId: 'AccessKeyId', accessKeySecret: 'AccessKeySecret', securityToken: 'OptionalSecurityToken', roleArn: 'acs:ram::123456789012****:role/example-role', roleSessionName: 'nacos-nodejs-sdk', policy: '{\"Version\":\"1\",\"Statement\":[]}', roleSessionExpiration: 3600, }), }; function createRoleArnProvider(options) { let cachedCredentials; return async () => { if (cachedCredentials && Date.parse(cachedCredentials.Expiration) - Date.now() > 3 * 60 * 1000) { return cachedCredentials; } // Call Aliyun STS AssumeRole with options.roleArn, options.roleSessionName, // options.policy, options.roleSessionExpiration, and the source AK/SK. cachedCredentials = await assumeRoleByAliyunSdk(options); return { AccessKeyId: cachedCredentials.AccessKeyId, AccessKeySecret: cachedCredentials.AccessKeySecret, SecurityToken: cachedCredentials.SecurityToken, Expiration: cachedCredentials.Expiration, }; }; } ``` -------------------------------- ### Get All Configurations Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/client-worker.md Retrieves all configuration strings within the current namespace. Use this to fetch all available configurations. ```typescript async getConfigs(): Promise> ``` ```typescript const configs = await worker.getConfigs(); console.log('Total configs:', configs.length); ``` -------------------------------- ### Complete DataClient Example Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/data-client.md Demonstrates the full lifecycle of using the DataClient, including initialization, subscribing to configuration updates, retrieving configurations, publishing new configurations, fetching available server units, and closing the client. Ensure the Nacos server is running and accessible at the specified address. ```typescript import { DataClient } from 'nacos'; async function main() { const client = new DataClient({ serverAddr: '127.0.0.1:8848', namespace: 'production', requestTimeout: 5000, }); // Subscribe to config changes client.subscribe( { dataId: 'app-config', group: 'DEFAULT_GROUP' }, (content) => { console.log('App config updated:', content); } ); // Retrieve config const config = await client.getConfig('database', 'DEFAULT_GROUP'); console.log('Database config:', config); // Publish new config const result = await client.publishSingle( 'feature-flags', 'DEFAULT_GROUP', 'new_feature_enabled=true' ); if (result) { console.log('Feature flag published'); } // Get all available units const units = await client.getAllUnits(); console.log('Units:', units); // Cleanup client.close(); } main().catch(console.error); ``` -------------------------------- ### Complete Snapshot API Example Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/snapshot.md Demonstrates how to use the Snapshot API to save, retrieve, batch save, and delete configurations. Includes error handling and verification of deletion. Ensure the Configuration object is properly initialized with a cache directory. ```typescript import { Snapshot } from 'nacos'; import { Configuration } from 'nacos'; async function main() { const config = new Configuration({ cacheDir: '/var/lib/nacos-cache', }); const snapshot = new Snapshot({ configuration: config }); // Listen for errors snapshot.on('error', (err) => { console.error(`Snapshot ${err.name}:`, err.message); }); // Save a configuration await snapshot.save('app@DEFAULT_GROUP', 'version=1.0.0'); // Retrieve it const cached = await snapshot.get('app@DEFAULT_GROUP'); console.log('Cached config:', cached); // Batch save multiple await snapshot.batchSave([ { key: 'db@prod', value: 'host=db.prod' }, { key: 'cache@prod', value: 'ttl=3600' }, ]); // Delete when no longer needed await snapshot.delete('app@DEFAULT_GROUP'); // Verify deletion const deleted = await snapshot.get('app@DEFAULT_GROUP'); console.log('After delete:', deleted); // null } main().catch(console.error); ``` -------------------------------- ### Offline Access Example Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/snapshot.md Illustrates how to implement offline access by first attempting to retrieve a configuration from the server and falling back to the local snapshot cache if the server is unavailable. ```APIDOC ## Offline Access ### Description Provides a fallback mechanism to access configurations from the local cache when the server is unavailable. ### Method Asynchronous function calls ### Endpoint N/A (SDK usage) ### Parameters - `dataId` (string) - The ID of the configuration data. - `group` (string) - The group of the configuration. ### Request Example ```typescript // Try server first, fall back to cache let config = await getConfigFromServer(dataId, group); if (!config) { config = await snapshot.get(`${dataId}@${group}`); if (config) { console.log('Using cached config (server unavailable)'); } } ``` ### Response - `config` (any) - The retrieved configuration, either from the server or the local cache. ``` -------------------------------- ### Install Nacos Node.js SDK Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/packages/nacos-naming/README.md Install the Nacos Node.js SDK using npm. This command saves the package as a dependency in your project. ```bash npm install nacos --save ``` -------------------------------- ### Bulk Updates Example Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/snapshot.md Demonstrates how to perform bulk updates to the local snapshot cache by saving multiple configuration entries simultaneously after a successful bulk fetch. ```APIDOC ## Bulk Updates ### Description Saves multiple configuration entries to the local snapshot cache in a single operation. ### Method `snapshot.batchSave(updates: Array<{key: string, value: any}>): Promise` ### Endpoint N/A (SDK method) ### Parameters - **updates** (Array<{key: string, value: any}>) - An array of objects, where each object contains a `key` and its corresponding `value` to be saved. - `key` (string) - The unique key identifying the configuration. - `value` (any) - The configuration content. ### Request Example ```typescript // Update cache after successful bulk fetch const updates = configs.map(cfg => ({ key: `${cfg.dataId}@${cfg.group}`, value: cfg.content })); await snapshot.batchSave(updates); ``` ### Response None (operation is asynchronous). ``` -------------------------------- ### Nacos Config Service Example (Direct Mode) Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/packages/nacos/README.md Initialize NacosConfigClient in direct mode, specifying the server address. This is an alternative to using Aliyun ACM. ```javascript // for direct mode const configClient = new NacosConfigClient({ serverAddr: '127.0.0.1:8848', }); ``` -------------------------------- ### Nacos Service Discovery Quick Start Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/README.md Illustrates how to create a NacosNamingClient, register a service instance, retrieve healthy instances, and subscribe to service changes. Requires a running Nacos server. ```typescript import { NacosNamingClient } from 'nacos'; // Create client const client = new NacosNamingClient({ logger: console, serverList: '127.0.0.1:8848', namespace: 'public', }); // Wait for ready await client.ready(); // Register instance await client.registerInstance('my-service', { ip: '192.168.1.100', port: 8080, weight: 1, ephemeral: true, }); // Get healthy instances const instances = await client.selectInstances('my-service'); // Subscribe to service changes client.subscribe('my-service', (hosts) => { console.log('Instances:', hosts); }); ``` -------------------------------- ### get Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/configuration.md Retrieves a specific configuration value by its key, or the entire configuration object if no key is provided. ```APIDOC ## get Get a configuration value. ```typescript get(configKey?: ClientOptionKeys): any ``` ### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | configKey | `ClientOptionKeys` | No | Configuration key to retrieve | ### Returns Returns the configuration value. If no key provided, returns the entire configuration object. ### Example ```typescript const timeout = config.get(ClientOptionKeys.REQUEST_TIMEOUT); console.log('Timeout:', timeout); // Get all configuration const allConfig = config.get(); console.log('All settings:', allConfig); ``` ``` -------------------------------- ### Nacos Naming Client Complete Example Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/nacos-naming-client.md Demonstrates registering an instance, subscribing to service changes, retrieving healthy instances, checking server status, and gracefully deregistering an instance using the Nacos Naming Client. ```javascript const { NacosNamingClient } = require('nacos'); async function main() { const client = new NacosNamingClient({ logger: console, serverList: '127.0.0.1:8848', namespace: 'public', }); await client.ready(); // Register instance await client.registerInstance('api-service', { ip: '192.168.1.100', port: 8080, weight: 1, ephemeral: true, metadata: { version: '1.0.0' } }); // Subscribe to service changes client.subscribe('api-service', (hosts) => { console.log('Available instances:'); hosts.forEach(host => { console.log(` ${host.ip}:${host.port} (healthy: ${host.healthy})`); }); }); // Get healthy instances const instances = await client.selectInstances('api-service'); console.log('Healthy instances:', instances); // Check server status console.log('Server status:', client.getServerStatus()); // Graceful shutdown setTimeout(async () => { await client.deregisterInstance('api-service', { ip: '192.168.1.100', port: 8080 }); }, 60000); } main().catch(console.error); ``` -------------------------------- ### Nacos Config Service Example (Aliyun ACM) Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/packages/nacos/README.md Initialize NacosConfigClient for Aliyun ACM with endpoint, namespace, and credentials. This client is used for managing configuration data. ```javascript import {NacosConfigClient} from 'nacos'; // ts const NacosConfigClient = require('nacos').NacosConfigClient; // js // for find address mode const configClient = new NacosConfigClient({ endpoint: 'acm.aliyun.com', namespace: '***************', accessKey: '***************', secretKey: '***************', requestTimeout: 6000, }); ``` -------------------------------- ### Nacos Config Client for Production with Aliyun Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/configuration.md Configure the client for production use with Aliyun services. This example uses environment variables for sensitive credentials and enables SSL. ```javascript const client = new NacosConfigClient({ endpoint: 'acm.aliyun.com', namespace: process.env.NACOS_NAMESPACE, accessKey: process.env.NACOS_ACCESS_KEY, secretKey: process.env.NACOS_SECRET_KEY, requestTimeout: 6000, ssl: true, }); ``` -------------------------------- ### IConfiguration Interface Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/types.md Configuration management interface for merging, attaching, getting, and modifying configuration settings. ```typescript interface IConfiguration { merge(config: any): IConfiguration; attach(config: any): IConfiguration; get(configKey?: ClientOptionKeys): any; has(configKey: ClientOptionKeys): boolean; set(configKey: ClientOptionKeys, target: any): IConfiguration; modify(configKey: ClientOptionKeys, changeHandler: (target: any) => any): IConfiguration; } ``` -------------------------------- ### Round-Robin Load Balancing Example Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/server-list-manager.md Illustrates the simple round-robin load balancing strategy implemented by ServerListManager. The index cycles through the server list, returning to the first server after reaching the end. ```typescript const serverList = [ '192.168.1.1:8848', '192.168.1.2:8848', '192.168.1.3:8848' ]; // index starts at 0 // First call: index % 3 = 0 → 192.168.1.1:8848 // Second call: index % 3 = 1 → 192.168.1.2:8848 // Third call: index % 3 = 2 → 192.168.1.3:8848 // Fourth call: index % 3 = 0 → 192.168.1.1:8848 (back to first) ``` -------------------------------- ### NacosConfigClient Direct Connection Setup Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/README.md Instantiate NacosConfigClient for direct connection to Nacos servers. Supports single server, multiple servers in an array, or a comma-separated string of server addresses. ```typescript // Single server const client = new NacosConfigClient({ serverAddr: '127.0.0.1:8848', }); ``` ```typescript // Multiple servers const client = new NacosConfigClient({ serverAddr: ['host1:8848', 'host2:8848', 'host3:8848'], }); ``` ```typescript // Comma-separated const client = new NacosConfigClient({ serverAddr: 'host1:8848,host2:8848,host3:8848', }); ``` -------------------------------- ### IConfiguration Interface Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/types.md Interface for configuration management, providing methods to merge, attach, get, check existence, set, and modify configurations. ```APIDOC ## IConfiguration Configuration management interface. ```typescript interface IConfiguration { merge(config: any): IConfiguration; attach(config: any): IConfiguration; get(configKey?: ClientOptionKeys): any; has(configKey: ClientOptionKeys): boolean; set(configKey: ClientOptionKeys, target: any): IConfiguration; modify(configKey: ClientOptionKeys, changeHandler: (target: any) => any): IConfiguration; } ``` ``` -------------------------------- ### POST Request Example Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/http-agent.md Use this to publish or update configuration content in Nacos. The request body should include the dataId, group, and content. ```typescript // Example: Publish configuration POST /v1/cs/configs Body: dataId=app&group=DEFAULT_GROUP&content=... ``` -------------------------------- ### POST Requests Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/http-agent.md Handles POST requests, commonly used for publishing or updating configuration data. Shows an example of publishing a configuration. ```APIDOC ## POST /v1/cs/configs ### Description Publish or update configuration data. ### Method POST ### Endpoint /v1/cs/configs ### Request Body - **dataId** (string) - Required - The ID of the configuration data. - **group** (string) - Required - The group the configuration belongs to. - **content** (string) - Required - The content of the configuration. ### Request Example ``` POST /v1/cs/configs Body: dataId=app&group=DEFAULT_GROUP&content=... ``` ``` -------------------------------- ### Get Configuration Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/packages/nacos-config/README.md Asynchronously retrieve configuration content using the `getConfig` method, providing the dataId and group. The retrieved content is then logged to the console. ```javascript // 主动拉取配置 const content= await configClient.getConfig('test', 'DEFAULT_GROUP'); console.log('getConfig = ',content); ``` -------------------------------- ### get Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/snapshot.md Retrieves a cached configuration from disk using a specified key. Returns the content as a string or null if not found. Emits an 'error' event on filesystem read failures. ```APIDOC ## get ### Description Retrieves a cached configuration from disk using a specified key. Returns the content as a string or null if not found. Emits an 'error' event on filesystem read failures. ### Parameters #### Path Parameters - **key** (string) - Required - Cache key (usually dataId@group format) ### Returns - `Promise` - A promise resolving to the cached content string, or `null` if not found. ### Behavior - Checks for snapshot file existence - Reads file with UTF-8 encoding - Returns `null` if file doesn't exist - Emits 'error' event if read fails (non-fatal) ### Throws - Emits 'error' event (does not throw) on filesystem read errors ### Example ```typescript const cached = await snapshot.get('app-config@DEFAULT_GROUP'); if (cached) { console.log('From cache:', cached); } ``` ``` -------------------------------- ### NacosConfigClient Address Lookup Mode Setup Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/README.md Instantiate NacosConfigClient using address lookup mode, which requires endpoint, server port, namespace, and authentication credentials. ```typescript const client = new NacosConfigClient({ endpoint: 'acm.aliyun.com', serverPort: 8080, namespace: 'my-namespace', accessKey: 'your-access-key', secretKey: 'your-secret-key', }); ``` -------------------------------- ### Constructor Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/configuration.md Initializes a new Configuration instance with optional initial settings. ```APIDOC ## Constructor ```typescript constructor(initConfig?: any) ``` ### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | initConfig | `object` | No | Initial configuration object | ### Example ```typescript import { Configuration } from 'nacos'; const config = new Configuration({ serverAddr: '127.0.0.1:8848', namespace: 'production', requestTimeout: 5000, }); ``` ``` -------------------------------- ### NacosNamingClient Initialization and Basic Operations Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/nacos-naming-client.md Demonstrates how to initialize the NacosNamingClient, register an instance, subscribe to service changes, select instances, and check server status. ```APIDOC ## NacosNamingClient Initialization and Basic Operations ### Description This example shows the fundamental usage of the `NacosNamingClient` including initialization, registering a service instance, subscribing to service updates, retrieving healthy instances, and checking the server's operational status. It also includes a mechanism for graceful shutdown by deregistering the instance. ### Initialization ```javascript const { NacosNamingClient } = require('nacos'); const client = new NacosNamingClient({ logger: console, serverList: '127.0.0.1:8848', namespace: 'public', }); await client.ready(); ``` ### Register Instance Registers a new service instance with Nacos. #### Method `registerInstance(serviceName, instance)` #### Parameters - **serviceName** (string) - The name of the service to register. - **instance** (Instance) - An object containing instance details like `ip`, `port`, `weight`, `ephemeral`, and `metadata`. #### Request Example ```javascript await client.registerInstance('api-service', { ip: '192.168.1.100', port: 8080, weight: 1, ephemeral: true, metadata: { version: '1.0.0' } }); ``` ### Subscribe to Service Changes Subscribes to receive updates on service instances. #### Method `subscribe(serviceName, listener)` #### Parameters - **serviceName** (string) - The name of the service to subscribe to. - **listener** (function) - A callback function that receives an array of `Host` objects representing the available instances. #### Request Example ```javascript client.subscribe('api-service', (hosts) => { console.log('Available instances:'); hosts.forEach(host => { console.log(` ${host.ip}:${host.port} (healthy: ${host.healthy})`); }); }); ``` ### Select Instances Retrieves a list of healthy instances for a given service. #### Method `selectInstances(serviceName, subscribe)` #### Parameters - **serviceName** (string) - The name of the service to query. - **subscribe** (boolean, optional) - Whether to subscribe to changes. Defaults to false. #### Response Example ```javascript const instances = await client.selectInstances('api-service'); console.log('Healthy instances:', instances); ``` ### Get Server Status Checks the current operational status of the Nacos server. #### Method `getServerStatus()` #### Response Example ```javascript console.log('Server status:', client.getServerStatus()); ``` ### Deregister Instance Removes a previously registered service instance. #### Method `deregisterInstance(serviceName, instance)` #### Parameters - **serviceName** (string) - The name of the service. - **instance** (Instance) - An object identifying the instance to deregister (e.g., `ip`, `port`). #### Request Example ```javascript setTimeout(async () => { await client.deregisterInstance('api-service', { ip: '192.168.1.100', port: 8080 }); }, 60000); ``` ``` -------------------------------- ### Nacos Config Service Operations Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/packages/nacos/README.md Perform operations like getting, subscribing to, publishing, and removing configuration data using NacosConfigClient. Use the 'test' dataId and 'DEFAULT_GROUP' group for these examples. ```javascript // get config once const content= await configClient.getConfig('test', 'DEFAULT_GROUP'); console.log('getConfig = ',content); // listen data changed configClient.subscribe({ dataId: 'test', group: 'DEFAULT_GROUP', }, content => { console.log(content); }); // publish config const content= await configClient.publishSingle('test', 'DEFAULT_GROUP', '测试'); console.log('getConfig = ',content); // remove config await configClient.remove('test', 'DEFAULT_GROUP'); ``` -------------------------------- ### Initialize NacosNamingClient Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/nacos-naming-client.md Instantiate NacosNamingClient with essential configuration including logger, server list, and namespace. Ensure the client is ready before use. ```javascript const { NacosNamingClient } = require('nacos'); const client = new NacosNamingClient({ logger: console, serverList: '127.0.0.1:8848', namespace: 'public', }); await client.ready(); ``` -------------------------------- ### Initialize ServerListManager Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/server-list-manager.md Demonstrates how to initialize ServerListManager with configuration options, including endpoint and server address. Ensure the manager is ready before use. ```typescript import { ServerListManager } from 'nacos'; import { Configuration } from 'nacos'; const config = new Configuration({ endpoint: 'acm.aliyun.com', serverAddr: '127.0.0.1:8848', }); const manager = new ServerListManager({ configuration: config }); await manager.ready(); ``` -------------------------------- ### Initialize Snapshot with Configuration Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/snapshot.md Demonstrates how to create a new Snapshot instance, providing it with a Configuration object that specifies the cache directory. ```typescript import { Snapshot } from 'nacos'; import { Configuration } from 'nacos'; const config = new Configuration({ cacheDir: '/tmp/nacos-cache', }); const snapshot = new Snapshot({ configuration: config }); ``` -------------------------------- ### Get config Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/client-worker.md Retrieves the content of a specific configuration from the Nacos server. ```APIDOC ## GET /v1/cs/configs ### Description Retrieves the content of a specific configuration from the Nacos server. ### Method GET ### Endpoint /v1/cs/configs ### Parameters #### Query Parameters - **dataId** (string) - Required - The ID of the configuration to retrieve. - **group** (string) - Required - The group of the configuration to retrieve. - **tenant** (string) - Optional - The tenant (namespace) ID. ### Response #### Success Response (200) - **content** (string) - The content of the configuration. #### Response Example { "content": "host=db.example.com\nport=5432" } ``` -------------------------------- ### Get Unit Identifier Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/client-worker.md Retrieves the unit identifier for the client worker. ```typescript get unit(): string ``` -------------------------------- ### Get Configuration Object Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/client-worker.md Retrieves the configuration object for the client worker. ```typescript get configuration(): IConfiguration ``` -------------------------------- ### NacosHttpError Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/errors.md Details about the NacosHttpError, including its properties, when it is thrown, and an example of how to handle it. ```APIDOC ## NacosHttpError ### Description HTTP-related error thrown during server communication. This error is typically encountered when there are issues communicating with the Nacos server, such as network problems, invalid responses, or timeouts. ### Properties - **url** (string) - The URL that was requested. - **params** (any) - The parameters sent with the request. - **body** (any) - The response body received from the server. - **unit** (string) - The target unit, if applicable. - **dataId** (string) - The Data ID involved in the request, if applicable. - **group** (string) - The group name involved in the request, if applicable. ### When Thrown - Failed HTTP request to Nacos server - Invalid server response - Timeout during request - Network connectivity issues - Server returned error status code ### Example Handling ```typescript import { NacosConfigClient } from 'nacos'; const client = new NacosConfigClient({ serverAddr: '127.0.0.1:8848', }); try { const config = await client.getConfig('app.config', 'DEFAULT_GROUP'); } catch (error) { if (error.name === 'NacosHttpError') { console.error('HTTP Error:', error.message); console.error('URL:', error.url); console.error('DataId:', error.dataId); } else { console.error('Other error:', error); } } ``` ``` -------------------------------- ### defaultEncoding Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/client-worker.md Gets the default encoding used by the client worker, typically 'utf8'. ```APIDOC ### defaultEncoding Get the default encoding (usually 'utf8'). ```typescript get defaultEncoding(): string ``` ``` -------------------------------- ### Initialize NacosNamingClient Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/configuration.md Instantiate the NacosNamingClient with essential configuration parameters. Note that `serverList` is used instead of `serverAddr`, and `logger` is a required option. ```javascript const { NacosNamingClient } = require('nacos'); const client = new NacosNamingClient({ logger: console, serverList: '127.0.0.1:8848', namespace: 'public', username: 'admin', password: 'password', ssl: false, }); ``` -------------------------------- ### Get Namespace ID Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/client-worker.md Retrieves the namespace ID configured for the client worker. ```typescript get namespace(): string ``` -------------------------------- ### Initialize Configuration Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/configuration.md Instantiate the Configuration class with initial settings. Supports specifying server address, namespace, and request timeout. ```typescript import { Configuration } from 'nacos'; const config = new Configuration({ serverAddr: '127.0.0.1:8848', namespace: 'production', requestTimeout: 5000, }); ``` -------------------------------- ### Get Snapshot Instance Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/client-worker.md Retrieves the snapshot (cache) instance used by the client worker. ```typescript get snapshot(): ISnapshot ``` -------------------------------- ### Get App Name Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/data-client.md Retrieves the application name configured in the DataClient options. This property is read-only. ```typescript get appName(): string ``` -------------------------------- ### Initialize NacosConfigClient (Direct Connection Mode) Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/packages/nacos-config/README.md Instantiate the NacosConfigClient using the direct connection mode, specifying the server address and port. Other parameters are the same as in the addressing mode. ```javascript // 下面的代码是直连模式 const configClient = new NacosConfigClient({ serverAddr: '127.0.0.1:8848', // 对端的 ip 和端口,其他参数同寻址模式 }); ``` -------------------------------- ### Get Default Encoding Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/client-worker.md Retrieves the default encoding used by the client worker, typically 'utf8'. ```typescript get defaultEncoding(): string ``` -------------------------------- ### Get HTTP Agent Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/client-worker.md Retrieves the HTTP agent used by the client worker for making requests. ```typescript get httpAgent(): HttpAgent ``` -------------------------------- ### Config Service - Get Config Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/README.md Retrieves the configuration content for a given data ID and group. ```APIDOC ## GET /nacos/v1/cs/configs ### Description Retrieves the configuration content for a specified data ID and group. ### Method GET ### Endpoint /nacos/v1/cs/configs ### Parameters #### Query Parameters - **dataId** (string) - Required - The ID of the configuration data. - **group** (string) - Required - The group of the configuration data. - **namespace** (string) - Optional - The namespace ID for the configuration. ### Response #### Success Response (200) - **content** (string) - The configuration content. #### Response Example ```json "your config content" ``` ``` -------------------------------- ### Constructor Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/nacos-config-client.md Initializes a new instance of the NacosConfigClient with specified options. Supports direct connection or address lookup modes. ```APIDOC ## Constructor ```typescript constructor(options: ClientOptions = {}) ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | options | `ClientOptions` | No | `{}` | Configuration options | ### Options (ClientOptions) See [configuration.md](../configuration.md) for detailed options. ### Example ```typescript import { NacosConfigClient } from 'nacos'; // Direct mode: connect directly to Nacos server const configClient = new NacosConfigClient({ serverAddr: '127.0.0.1:8848', namespace: 'development', requestTimeout: 5000, }); // Address lookup mode (for Aliyun) const configClient = new NacosConfigClient({ endpoint: 'acm.aliyun.com', namespace: 'production', accessKey: 'your-access-key', secretKey: 'your-secret-key', }); await configClient.ready(); ``` ``` -------------------------------- ### Configure Credentials via Environment Variables Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/README.md Set Aliyun cloud credentials using environment variables for automatic SDK detection. ```bash export ALIBABA_CLOUD_ACCESS_KEY_ID=AccessKeyId export ALIBABA_CLOUD_ACCESS_KEY_SECRET=AccessKeySecret export ALIBABA_CLOUD_SECURITY_TOKEN=SecurityToken ``` -------------------------------- ### Get HTTP Client Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/data-client.md Retrieves the underlying HTTP client instance used by the DataClient. Defaults to urllib. ```typescript get httpclient(): any ``` -------------------------------- ### NacosConfigClient Initialization Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/packages/nacos-config/README.md Demonstrates how to initialize the NacosConfigClient using either the ACM addressing mode or direct connection mode. ```APIDOC ## Initialization ### ACM Addressing Mode ```js const configClient = new NacosConfigClient({ endpoint: 'acm.aliyun.com', // acm 控制台查看 namespace: '***************', // acm 控制台查看 accessKey: '***************', // acm 控制台查看 secretKey: '***************', // acm 控制台查看 requestTimeout: 6000, // 请求超时时间,默认6s }); ``` ### Direct Connection Mode ```js const configClient = new NacosConfigClient({ serverAddr: '127.0.0.1:8848', // 对端的 ip 和端口,其他参数同寻址模式 }); ``` ``` -------------------------------- ### Set Alibaba Cloud Credentials via Environment Variables Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/configuration.md Configure Aliyun credentials using environment variables. These are automatically detected if not explicitly set in the client configuration. ```bash export ALIBABA_CLOUD_ACCESS_KEY_ID=your-access-key-id export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your-access-key-secret export ALIBABA_CLOUD_SECURITY_TOKEN=your-security-token # optional ``` -------------------------------- ### Get Cache Directory Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/snapshot.md Retrieves the path to the directory where snapshots are cached locally. The default path is `~/.node-diamond-client-cache`. ```APIDOC ## Get Cache Directory ### Description Retrieves the configured cache directory path. ### Method Getter ### Endpoint N/A (SDK property) ### Parameters None ### Response - **cacheDir** (string) - The path to the cache directory. ``` -------------------------------- ### IClientWorker Interface Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/types.md Core worker interface for configuration operations like getting, publishing, and removing configurations. ```typescript interface IClientWorker { getConfig(dataId: string, group: string, options?: UnitOptions): Promise; publishSingle(dataId: string, group: string, content: string, options?: UnitOptions): Promise; remove(dataId: string, group: string, options?: UnitOptions): Promise; publishAggr(dataId: string, group: string, datumId: string, content: string, options?: UnitOptions): Promise; removeAggr(dataId: string, group: string, datumId: string, options?: UnitOptions): Promise; batchGetConfig(dataIds: string[], group: string, options?: UnitOptions): Promise; batchQuery(dataIds: string[], group: string, options?: UnitOptions): Promise; subscribe(reg: CommonInputOptions, listener: Subscriber): any; unSubscribe(reg: CommonInputOptions, listener?: ListenFunc): any; getConfigs(): Promise>; close(): void; } ``` -------------------------------- ### HttpAgent Constructor Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/http-agent.md Initializes the HttpAgent with configuration options. The constructor takes a single options object which must include a configuration instance. ```APIDOC ## Constructor ```typescript constructor(options: any) ``` ### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | options | `any` | Yes | Configuration object containing configuration instance | ### Initialization The constructor stores the options and uses them to access configuration and server manager. ### Example ```typescript import { HttpAgent } from 'nacos'; import { Configuration } from 'nacos'; const config = new Configuration({ serverAddr: '127.0.0.1:8848', requestTimeout: 5000, }); const agent = new HttpAgent({ configuration: config }); ``` ``` -------------------------------- ### DELETE Request Example Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/http-agent.md Use this to remove a configuration from Nacos. Specify the dataId and group of the configuration to be deleted. ```typescript // Example: Remove configuration DELETE /v1/cs/configs?dataId=app&group=DEFAULT_GROUP ``` -------------------------------- ### IClientWorker Interface Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/types.md The core worker interface for configuration operations, including getting, publishing, removing, and subscribing to configurations. ```APIDOC ## IClientWorker Core worker interface for configuration operations. ```typescript interface IClientWorker { getConfig(dataId: string, group: string, options?: UnitOptions): Promise; publishSingle(dataId: string, group: string, content: string, options?: UnitOptions): Promise; remove(dataId: string, group: string, options?: UnitOptions): Promise; publishAggr(dataId: string, group: string, datumId: string, content: string, options?: UnitOptions): Promise; removeAggr(dataId: string, group: string, datumId: string, options?: UnitOptions): Promise; batchGetConfig(dataIds: string[], group: string, options?: UnitOptions): Promise; batchQuery(dataIds: string[], group: string, options?: UnitOptions): Promise; subscribe(reg: CommonInputOptions, listener: Subscriber): any; unSubscribe(reg: CommonInputOptions, listener?: ListenFunc): any; getConfigs(): Promise>; close(): void; } ``` ``` -------------------------------- ### attach Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/configuration.md Creates a new Configuration instance with merged properties, leaving the original instance unchanged. ```APIDOC ## attach Create a new Configuration with merged values. ```typescript attach(config: object): Configuration ``` ### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | config | `object` | Yes | Configuration object to attach | ### Returns Returns a new `Configuration` instance without modifying the original. ### Behavior Creates a new Configuration object with merged properties from both configurations. ### Example ```typescript const baseConfig = new Configuration({ serverAddr: '127.0.0.1:8848', }); const prodConfig = baseConfig.attach({ namespace: 'production', ssl: true, }); // Original unchanged console.log(baseConfig.get('namespace')); // undefined console.log(prodConfig.get('namespace')); // 'production' ``` ``` -------------------------------- ### Get Cache Directory Path Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/snapshot.md Retrieves the configured cache directory path for snapshots. The default path is `~/.node-diamond-client-cache`. ```typescript get cacheDir(): string ``` -------------------------------- ### Get Single Configuration Source: https://github.com/nacos-group/nacos-sdk-nodejs/blob/master/_autodocs/api-reference/nacos-config-client.md Retrieve a specific configuration by its dataId and group. Optionally specify a unit and configuration type. ```typescript const content = await configClient.getConfig('database', 'DEFAULT_GROUP'); console.log('Database config:', content); const jsonConfig = await configClient.getConfig('app-settings', 'production', { unit: 'unit1', type: 'json' }); ```