### List sub-accounts examples Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/provisioning.md Examples demonstrating how to list all sub-accounts, filter by status, or filter by name prefix. ```javascript const cloudinary = require('cloudinary').v2; cloudinary.provisioning.account.sub_accounts().then(result => { result.sub_accounts.forEach(account => { console.log(`${account.cloud_name} (${account.name}): ${account.enabled ? 'enabled' : 'disabled'}`); }); }).catch(error => { console.error('Failed:', error); }); ``` ```javascript const cloudinary = require('cloudinary').v2; // List only enabled sub-accounts cloudinary.provisioning.account.sub_accounts(true).then(result => { console.log(`Active accounts: ${result.sub_accounts.length}`); }); ``` ```javascript const cloudinary = require('cloudinary').v2; cloudinary.provisioning.account.sub_accounts(undefined, [], 'staging-').then(result => { result.sub_accounts.forEach(account => { console.log(account.name); }); }); ``` -------------------------------- ### Delete asset examples Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/uploader.md Examples demonstrating basic asset deletion and deletion with resource type configuration. ```javascript const cloudinary = require('cloudinary').v2; cloudinary.uploader.destroy('my-image').then(result => { console.log('Deleted:', result.result); }).catch(error => { console.error('Delete failed:', error); }); ``` ```javascript const cloudinary = require('cloudinary').v2; cloudinary.uploader.destroy('my-image', { resource_type: 'video' }).then(result => { if (result.result === 'ok') { console.log('Video deleted successfully'); } }).catch(error => { if (error.message.includes('not found')) { console.log('Asset already deleted'); } }); ``` -------------------------------- ### Create Search Instance Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/search.md Method signature and usage example for initializing a new search query. ```javascript static instance(): Search ``` ```javascript const cloudinary = require('cloudinary').v2; const search = cloudinary.search.instance() .expression('resource_type:image AND tags:vacation') .max_results(50) .execute() .then(result => { console.log('Found:', result.total_count); result.resources.forEach(asset => { console.log(asset.public_id); }); }); ``` -------------------------------- ### Rename asset example Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/uploader.md Example demonstrating how to rename an asset and handle potential naming conflicts. ```javascript const cloudinary = require('cloudinary').v2; cloudinary.uploader.rename('old-name', 'new-name').then(result => { console.log('Renamed successfully'); }).catch(error => { if (error.message.includes('already exists')) { console.log('Target public_id already in use'); } }); ``` -------------------------------- ### Install Cloudinary SDK Source: https://github.com/cloudinary/cloudinary_npm/blob/master/README.md Command to install the Cloudinary package via npm. ```bash npm install cloudinary ``` -------------------------------- ### Create ZIP archive example Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/uploader.md Demonstrates creating a ZIP archive from a list of public IDs. ```javascript const cloudinary = require('cloudinary').v2; cloudinary.uploader.create_archive({ public_ids: ['image1', 'image2', 'image3'], target_format: 'zip', target_public_id: 'my-archive' }).then(result => { console.log('Archive URL:', result.secure_url); }).catch(error => { console.error('Archive creation failed:', error); }); ``` -------------------------------- ### Create Sub-Account Methods Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/provisioning.md Examples for creating new sub-accounts with basic settings, custom attributes, or cloned configurations from a base account. ```javascript const cloudinary = require('cloudinary').v2; cloudinary.provisioning.account.create_sub_account( 'Staging Environment', 'staging-app-2024' ).then(account => { console.log(`Created: ${account.cloud_name}`); console.log(`ID: ${account.id}`); }).catch(error => { if (error.message.includes('already exists')) { console.log('Cloud name already in use'); } }); ``` ```javascript const cloudinary = require('cloudinary').v2; cloudinary.provisioning.account.create_sub_account( 'Client XYZ', 'client-xyz-prod', { client_id: '12345', environment: 'production', billing_code: 'CLIENT-XYZ' }, true ).then(account => { console.log('Account created with metadata'); }); ``` ```javascript const cloudinary = require('cloudinary').v2; cloudinary.provisioning.account.create_sub_account( 'New Staging', 'new-staging-env', {}, true, 'template-account-id' // Copy settings from this account ).then(account => { console.log('Account created with cloned settings'); }); ``` -------------------------------- ### Install Cloudinary CLI Source: https://github.com/cloudinary/cloudinary_npm/blob/master/docs/platform-capabilities.md Install the Cloudinary CLI tool for performing administrative, upload, and search operations from the terminal. ```bash pipx install cloudinary-cli # command: cld ``` -------------------------------- ### Create ZIP convenience method example Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/uploader.md Demonstrates using the create_zip convenience method to generate a ZIP archive. ```javascript const cloudinary = require('cloudinary').v2; cloudinary.uploader.create_zip({ public_ids: ['photo1', 'photo2'], target_public_id: 'photos-zip' }).then(result => { console.log('Created:', result.secure_url); }); ``` -------------------------------- ### Static Search Methods Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/search.md Signatures and usage examples for static search configuration methods. ```javascript static expression(value: string): Search ``` ```javascript const cloudinary = require('cloudinary').v2; cloudinary.search .expression('format:jpg AND width > 800') .max_results(20) .execute() .then(result => { console.log('Results:', result.resources.length); }); ``` ```javascript static max_results(value: number): Search ``` ```javascript static next_cursor(value: string): Search ``` ```javascript static aggregate(value: string): Search ``` ```javascript static with_field(value: string | string[]): Search ``` ```javascript static fields(value: string | string[]): Search ``` ```javascript static sort_by(field_name: string, dir?: string): Search ``` ```javascript static ttl(newTtl: number): Search ``` ```javascript static execute(options?: AdminApiOptions, callback?: ResponseCallback): Promise ``` -------------------------------- ### Method Documentation Template Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/README.md Standard structure for documenting SDK methods, including signature, parameters, and usage examples. ```markdown ## upload() Upload a file to Cloudinary. function upload(file: string | Buffer, options?: UploadApiOptions, callback?: UploadResponseCallback): Promise | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | file | string \| Buffer | Yes | — | File path, URL, or buffer | | options | UploadApiOptions | No | {} | Upload options | | callback | UploadResponseCallback | No | undefined | Optional callback | Return type: Promise Example: await cloudinary.uploader.upload('/path/to/file.jpg', { public_id: 'my-image' }); Source: lib/v2/uploader.js ``` -------------------------------- ### Client-side Stream Upload Example Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/uploader.md Demonstrates creating a writable stream for unsigned uploads and piping file data from a browser input element. ```javascript const cloudinary = require('cloudinary').v2; const stream = cloudinary.uploader.unsigned_upload_stream('my-unsigned-preset', { public_id: 'client-upload' }); stream.on('success', (result) => { console.log('Upload URL:', result.secure_url); }); // In browser context, pipe from FormData or blob inputElement.addEventListener('change', (e) => { const file = e.target.files[0]; file.stream().pipe(stream); }); ``` -------------------------------- ### Apply Metadata to Existing Asset Example Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/uploader.md Shows how to apply transformations and tags to an existing asset using the explicit method. ```javascript const cloudinary = require('cloudinary').v2; cloudinary.uploader.explicit('my-image', { type: 'upload', resource_type: 'image', eager: { width: 100, height: 100, crop: 'fill' }, tags: ['profile', 'important'] }).then(result => { console.log('Asset updated'); }).catch(error => { console.error('Update failed:', error); }); ``` -------------------------------- ### Implement a Custom Cache Adapter Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/cache.md Example of extending CacheAdapter to create a custom storage backend using a Map, then registering it with the Cache module. ```javascript class MyCustomCache extends cloudinary.Cache.CacheAdapter { constructor() { super(); this.store = new Map(); } get(publicId, type, resourceType, transformation, format) { const key = `${publicId}:${type}:${resourceType}:${transformation}:${format}`; return this.store.get(key); } set(publicId, type, resourceType, transformation, format, value) { const key = `${publicId}:${type}:${resourceType}:${transformation}:${format}`; this.store.set(key, value); return value; } flushAll() { this.store.clear(); } } cloudinary.Cache.setAdapter(new MyCustomCache()); ``` -------------------------------- ### Clear all tags example Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/uploader.md Usage example for removing all tags from a list of public IDs. ```javascript const cloudinary = require('cloudinary').v2; cloudinary.uploader.remove_all_tags(['image1', 'image2']).then(result => { console.log('All tags removed'); }).catch(error => { console.error('Failed:', error); }); ``` -------------------------------- ### Add Cloudinary developer skills Source: https://github.com/cloudinary/cloudinary_npm/blob/master/docs/platform-capabilities.md Install developer skills to assist with documentation lookups and transformation URL generation. ```bash npx skills add cloudinary-devs/skills ``` -------------------------------- ### Delete assets Source: https://github.com/cloudinary/cloudinary_npm/blob/master/docs/search-and-manage-assets.md Demonstrates single asset deletion and provides examples for bulk or prefix-based deletion. ```javascript await cloudinary.uploader.destroy('examples/uploaded-sample'); // one asset // cloudinary.api.delete_resources([...ids]) // bulk — double-check inputs // cloudinary.api.delete_resources_by_prefix('examples/') // by prefix — extremely destructive ``` -------------------------------- ### Get a specific config value Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/config.md Retrieve a single configuration parameter by passing its key as a string. ```javascript const cloudinary = require('cloudinary'); const apiKey = cloudinary.config('api_key'); ``` -------------------------------- ### Generate Picture Tag with Media Queries Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/url-generation.md Example of creating a picture element with multiple source definitions based on screen width, including fallback image options. ```javascript const cloudinary = require('cloudinary').v2; const html = cloudinary.picture('my-image', { sources: [ { min_width: 1600, transformation: { crop: 'fill', width: 1200, aspect_ratio: 2 } }, { min_width: 800, transformation: { crop: 'fill', width: 800, aspect_ratio: 2.3 } }, { max_width: 799, transformation: { crop: 'fill', width: 400, gravity: 'auto' } } ], quality: 'auto', fetch_format: 'auto' }); // // // // // ``` -------------------------------- ### Update Sub-Account Methods Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/provisioning.md Examples for modifying existing sub-account status or updating custom metadata attributes. ```javascript const cloudinary = require('cloudinary').v2; cloudinary.provisioning.account.update_sub_account('12345', undefined, undefined, {}, false).then(account => { console.log(`Account disabled`); }).catch(error => { console.error('Update failed:', error); }); ``` ```javascript const cloudinary = require('cloudinary').v2; cloudinary.provisioning.account.update_sub_account( '12345', undefined, undefined, { status: 'archived', last_reviewed: new Date().toISOString() } ).then(account => { console.log('Metadata updated'); }); ``` -------------------------------- ### Get details of a specific upload preset Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/api.md Retrieves configuration details for a single upload preset by name. ```javascript function upload_preset(name: string, options?: AdminApiOptions, callback?: ResponseCallback): Promise ``` ```javascript const cloudinary = require('cloudinary').v2; cloudinary.api.upload_preset('my-preset').then(result => { console.log('Preset:', result); }).catch(error => { console.error('Not found:', error); }); ``` -------------------------------- ### Get current configuration Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/config.md Retrieve the active configuration object to access settings like the cloud name. ```javascript const cloudinary = require('cloudinary'); const config = cloudinary.config(); console.log(config.cloud_name); // outputs cloud name ``` -------------------------------- ### Remove tag example Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/uploader.md Usage example for removing a specific tag from a list of public IDs. ```javascript const cloudinary = require('cloudinary').v2; cloudinary.uploader.remove_tag('temp', ['image1']).then(result => { console.log('Tag removed'); }).catch(error => { console.error('Tag removal failed:', error); }); ``` -------------------------------- ### Provision a cloud using the CLI Source: https://github.com/cloudinary/cloudinary_npm/blob/master/docs/get-credentials.md Use the CLI to automatically generate credentials and save them to your .env file. ```bash npx @cloudinary/cloud ``` -------------------------------- ### Configure and use FileKeyValueStorage Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/cache.md Initializes the file-based cache adapter and demonstrates how subsequent URL generation calls retrieve results from the cache. ```javascript const cloudinary = require('cloudinary').v2; const FileKeyValueStorage = require('cloudinary/lib/cache/FileKeyValueStorage'); // Configure Cloudinary cloudinary.config({ cloud_name: 'my-cloud', api_key: 'my-api-key', api_secret: 'my-api-secret' }); // Enable file-based caching const cacheAdapter = new FileKeyValueStorage(); cloudinary.Cache.setAdapter(cacheAdapter); // First call: generates URL and caches it const url1 = cloudinary.url('profile-photo', { width: 200, height: 200, crop: 'fill', gravity: 'face' }); console.log('Generated:', url1); // Second call: retrieves from cache (no generation overhead) const url2 = cloudinary.url('profile-photo', { width: 200, height: 200, crop: 'fill', gravity: 'face' }); console.log('From cache:', url2); console.log('Same:', url1 === url2); // true // Clear cache when needed cloudinary.Cache.flushAll(); ``` -------------------------------- ### Run Development Commands Source: https://github.com/cloudinary/cloudinary_npm/blob/master/AGENTS.md Use these npm scripts for dependency management, linting, and testing. ```bash npm install # install dependencies npm test # lint + unit tests + type declaration tests npm run test:unit # mocha unit tests only (mocked, no network) npm run lint # eslint npm run dtslint # TypeScript declaration tests npm run test-with-temp-cloud # full integration tests against a temporary cloud (CI) ``` -------------------------------- ### transformation() Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/api.md Get details of a specific named transformation. ```APIDOC ## transformation() ### Description Get details of a specific named transformation. ### Signature `function transformation(name: string, options?: AdminApiOptions, callback?: ResponseCallback): Promise` ### Parameters - **name** (string) - Required - Transformation name - **options** (AdminApiOptions) - Optional - Query options - **callback** (ResponseCallback) - Optional - Optional Node-style callback ### Example ```javascript const cloudinary = require('cloudinary').v2; cloudinary.api.transformation('thumbnail').then(result => { console.log('Definition:', result.definition); }).catch(error => { console.error('Failed:', error); }); ``` ``` -------------------------------- ### Get transformation details Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/api.md Fetch the definition of a specific named transformation. ```javascript function transformation(name: string, options?: AdminApiOptions, callback?: ResponseCallback): Promise ``` ```javascript const cloudinary = require('cloudinary').v2; cloudinary.api.transformation('thumbnail').then(result => { console.log('Definition:', result.definition); }).catch(error => { console.error('Failed:', error); }); ``` -------------------------------- ### Get sub-account details Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/provisioning.md Retrieves details for a specific sub-account using its ID. ```javascript const cloudinary = require('cloudinary').v2; cloudinary.provisioning.account.sub_account('12345').then(account => { console.log(`Name: ${account.name}`); console.log(`Cloud: ${account.cloud_name}`); console.log(`Enabled: ${account.enabled}`); console.log(`Created: ${account.created_at}`); }).catch(error => { console.error('Not found:', error); }); ``` -------------------------------- ### Configure for development Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/configuration.md Standard configuration pattern for local development environments. ```javascript cloudinary.config({ cloud_name: 'my-cloud-dev', api_key: 'dev-key', api_secret: 'dev-secret', debug: true }); ``` -------------------------------- ### resources(options, callback) Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/api.md Lists all assets in your account with support for pagination and filtering. ```APIDOC ## resources(options, callback) ### Description Lists assets with support for pagination, filtering by prefix, tags, context, and resource type. Returns a maximum of assets limited by max_results. ### Parameters - **options** (AdminAndResourceOptions) - Optional - Listing and filtering options - **callback** (ResponseCallback) - Optional - Optional Node-style callback ### Return Type Promise - Array of assets with pagination ### Example ```javascript cloudinary.api.resources({ max_results: 100, resource_type: 'image', type: 'upload' }).then(result => { result.resources.forEach(asset => { console.log(`${asset.public_id} (${asset.format})`); }); }); ``` ``` -------------------------------- ### get(publicId, options) Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/cache.md Retrieves a previously cached URL if a matching entry exists. ```APIDOC ## get(publicId, options) ### Description Returns a previously cached URL if a matching entry exists. The options object is converted to a transformation string for cache lookup. Returns undefined if no cache adapter is set. ### Parameters - **publicId** (string) - Required - Asset public ID - **options** (object) - Optional - Transformation options used to generate the URL ### Returns - **any** - Cached URL or undefined if not found ``` -------------------------------- ### Initialize Cloudinary SDK Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/MAIN_REFERENCE.md Configure the SDK using credentials or an environment variable. ```javascript const cloudinary = require('cloudinary').v2; cloudinary.config({ cloud_name: 'my-cloud', api_key: 'my-api-key', api_secret: 'my-api-secret' }); ``` ```bash export CLOUDINARY_URL=cloudinary://api_key:api_secret@cloud_name ``` -------------------------------- ### Use different provisioning credentials Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/provisioning.md Demonstrates how to override default credentials by passing a configuration object to a provisioning API method. ```javascript const cloudinary = require('cloudinary').v2; cloudinary.provisioning.account.sub_accounts(undefined, [], undefined, { account_id: 'other-account', provisioning_api_key: 'other-key', provisioning_api_secret: 'other-secret' }).then(result => { console.log('Retrieved sub-accounts from other account'); }); ``` -------------------------------- ### Initialize Cloudinary Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/INDEX.md Configure the SDK using environment variables or a configuration object. ```javascript const cloudinary = require('cloudinary').v2; // From environment variable // export CLOUDINARY_URL=cloudinary://key:secret@cloud // Or programmatically cloudinary.config({ cloud_name: 'my-cloud', api_key: 'my-key', api_secret: 'my-secret' }); ``` -------------------------------- ### Captioning Analysis JSON Response Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/auth-and-analysis.md Example JSON response structure for an image captioning analysis request. ```json { "data": { "entity": "my-image", "analysis": { "captions": [ { "text": "a person sitting on a bench", "confidence": 0.95 } ] } }, "request_id": "abc123def456" } ``` -------------------------------- ### Basic programmatic configuration Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/configuration.md Initializes the Cloudinary SDK with core credentials. ```javascript const cloudinary = require('cloudinary').v2; cloudinary.config({ cloud_name: 'my-cloud', api_key: 'my-api-key', api_secret: 'my-api-secret' }); ``` -------------------------------- ### Get API URL Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/utils.md Retrieves the base URL for API calls, optionally including an action path. ```javascript function api_url(action?: string, options?: ConfigAndUrlOptions): string ``` ```javascript const cloudinary = require('cloudinary').v2; const uploadUrl = cloudinary.utils.api_url('upload'); // https://api.cloudinary.com/v1_1/{cloud_name}/upload ``` -------------------------------- ### Get Cache Adapter Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/cache.md Retrieves the currently active cache adapter instance or undefined if none is set. ```javascript function getAdapter(): CacheAdapter | undefined ``` ```javascript const cloudinary = require('cloudinary').v2; if (cloudinary.Cache.getAdapter()) { console.log('URL caching is enabled'); } else { console.log('No cache adapter configured'); } ``` -------------------------------- ### Configure FileKeyValueStorage Adapter Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/cache.md Initializes the file system-based cache adapter to store URLs in a local directory. ```javascript const cloudinary = require('cloudinary').v2; const FileKeyValueStorage = require('cloudinary/lib/cache/FileKeyValueStorage'); const adapter = new FileKeyValueStorage({ directory: './url-cache', // Optional: cache directory ttl: 86400 // Optional: time-to-live in seconds }); cloudinary.Cache.setAdapter(adapter); ``` -------------------------------- ### Configure for production Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/configuration.md Secure configuration pattern using environment variables for sensitive credentials. ```javascript cloudinary.config({ cloud_name: process.env.CLOUDINARY_CLOUD, api_key: process.env.CLOUDINARY_KEY, api_secret: process.env.CLOUDINARY_SECRET, secure: true, sign_url: true }); ``` -------------------------------- ### Create a new folder Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/api.md Creates a new folder at the specified path. ```javascript function create_folder(path: string, options?: AdminApiOptions, callback?: ResponseCallback): Promise ``` ```javascript const cloudinary = require('cloudinary').v2; cloudinary.api.create_folder('media/photos/2024').then(result => { console.log('Folder created'); }).catch(error => { console.error('Failed:', error); }); ``` -------------------------------- ### Override configuration precedence Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/configuration.md Demonstrates how programmatic configuration calls take precedence over environment variables. ```javascript // Set from environment process.env.CLOUDINARY_URL = 'cloudinary://key:secret@cloud'; // Create config object (takes precedence) cloudinary.config({ cloud_name: 'my-cloud', secure: true }); // This value will use 'my-cloud' from config(), not from env console.log(cloudinary.config('cloud_name')); ``` -------------------------------- ### create_folder(path, options, callback) Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/api.md Creates a new folder. ```APIDOC ## create_folder(path, options, callback) ### Description Create a new folder. ### Parameters - **path** (string) - Required - New folder path - **options** (AdminApiOptions) - Optional - Creation options - **callback** (ResponseCallback) - Optional - Optional Node-style callback ### Return Type Promise - Creation result ``` -------------------------------- ### upload_presets() Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/api.md Lists all configured upload presets. ```APIDOC ## upload_presets() ### Description List all upload presets. ### Signature `function upload_presets(options?: AdminApiOptions, callback?: ResponseCallback): Promise` ### Example ```javascript const cloudinary = require('cloudinary').v2; cloudinary.api.upload_presets().then(result => { result.presets.forEach(preset => { console.log(`${preset.name} (${preset.unsigned ? 'unsigned' : 'signed'})`); }); }).catch(error => { console.error('Failed:', error); }); ``` ``` -------------------------------- ### Object Detection Analysis JSON Response Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/auth-and-analysis.md Example JSON response structure for an object detection analysis request using the COCO dataset. ```json { "data": { "entity": "street-scene", "analysis": { "objects": [ { "name": "person", "confidence": 0.98 }, { "name": "car", "confidence": 0.87 }, { "name": "building", "confidence": 0.92 } ] } }, "request_id": "xyz789abc" } ``` -------------------------------- ### usage() Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/api.md Retrieves account storage and transformation usage statistics. ```APIDOC ## usage() ### Description Get account storage and transformation usage for a specific date. ### Signature `function usage(options?: AdminApiOptions, callback?: ResponseCallback): Promise` ### Parameters - **options.date** (string) - Optional - Date in YYYY-MM-DD format (Default: today) - **options** (AdminApiOptions) - Optional - Query options - **callback** (ResponseCallback) - Optional - Optional Node-style callback ### Example ```javascript const cloudinary = require('cloudinary').v2; cloudinary.api.usage().then(result => { console.log('Transformations:', result.transformations); console.log('Storage:', result.storage); console.log('Bandwidth:', result.bandwidth); }).catch(error => { console.error('Failed:', error); }); ``` ``` -------------------------------- ### Retrieve client-side configuration Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/url-generation.md Returns a JSON string of non-sensitive configuration parameters suitable for initializing frontend SDKs. ```javascript const cloudinary = require('cloudinary').v2; const config = cloudinary.cloudinary_js_config(); // Rendered in HTML template: // ``` -------------------------------- ### Get Cached URL Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/cache.md Retrieves a cached URL based on the public ID and transformation options. Returns undefined if no cache adapter is configured or no match is found. ```javascript function get(publicId: string, options: object): any ``` ```javascript const cloudinary = require('cloudinary').v2; const options = { width: 300, crop: 'fill', quality: 'auto' }; const cached = cloudinary.Cache.get('my-image', options); if (cached) { console.log('From cache:', cached); } else { const url = cloudinary.url('my-image', options); console.log('Generated:', url); } ``` -------------------------------- ### Configure security settings Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/configuration.md Sets parameters for URL signing and authentication tokens. ```javascript cloudinary.config({ sign_url: true, long_url_signature: false, auth_token: { key: '1234567890abcdef', duration: 3600 } }); ``` -------------------------------- ### Configure CLOUDINARY_ACCOUNT_URL environment variable Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/configuration.md Sets the account and provisioning API configuration. ```bash export CLOUDINARY_ACCOUNT_URL=account://12345:prov_key:prov_secret ``` -------------------------------- ### Reinitialize from environment Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/configuration.md Force the SDK to reload configuration settings from environment variables. ```javascript cloudinary.config(true); // Reload from env vars ``` -------------------------------- ### CLI provisioning flags Source: https://github.com/cloudinary/cloudinary_npm/blob/master/docs/get-credentials.md Customize the provisioning process with flags for IP restrictions, JSON output, or forcing an overwrite of existing credentials. ```bash npx @cloudinary/cloud --ip # allow delivery to another viewer IP (max 3) npx @cloudinary/cloud --json # raw response, for programmatic use npx @cloudinary/cloud --force # replace an existing CLOUDINARY_URL in ./.env ``` -------------------------------- ### Cloudinary SDK Entry Points Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/MAIN_REFERENCE.md The SDK provides two primary entry points for interacting with the Cloudinary service. ```APIDOC ## SDK Entry Points ### V2 API (Recommended) `require('cloudinary').v2` - Provides a promise-based interface for all operations. ### V1 API (Legacy) `require('cloudinary')` - Provides a callback-based interface for backward compatibility. ``` -------------------------------- ### Configure Provisioning API settings Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/configuration.md Sets credentials for the Provisioning API. ```javascript cloudinary.config({ account_id: 'my-account-id', provisioning_api_key: 'prov-key', provisioning_api_secret: 'prov-secret' }); ``` -------------------------------- ### resources_by_context(key, value, options, callback) Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/api.md Find assets by context (metadata key-value pairs). ```APIDOC ## resources_by_context(key, value, options, callback) ### Description Find assets by context (metadata key-value pairs). ### Parameters - **key** (string) - Required - Context key to search - **value** (string) - Optional - Context value to match - **options** (AdminAndResourceOptions) - Optional - Query options - **callback** (ResponseCallback) - Optional - Optional Node-style callback ### Return Type Promise - Assets matching context criteria ### Example ```javascript cloudinary.api.resources_by_context('category', 'landscape').then(result => { console.log('Landscape images:', result.resources.length); }); ``` ``` -------------------------------- ### Complete account management workflow Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/provisioning.md Illustrates a full workflow for listing, creating, retrieving, and updating sub-accounts, as well as listing users. ```javascript const cloudinary = require('cloudinary').v2; // List and manage sub-accounts async function manageAccounts() { try { // List existing accounts const list = await cloudinary.provisioning.account.sub_accounts(); console.log(`Total sub-accounts: ${list.sub_accounts.length}`); // Create new staging account const stagingAccount = await cloudinary.provisioning.account.create_sub_account( 'Staging Environment', 'staging-app-dev', { environment: 'staging', team: 'backend' } ); console.log(`Created: ${stagingAccount.cloud_name}`); // Get account details const details = await cloudinary.provisioning.account.sub_account(stagingAccount.id); console.log(`Account details:`, details); // Update custom attributes await cloudinary.provisioning.account.update_sub_account( stagingAccount.id, undefined, undefined, { created_date: new Date().toISOString() } ); // List users in main account const users = await cloudinary.provisioning.account.users(); console.log(`Total users: ${users.users.length}`); } catch (error) { console.error('Error:', error.message); } } manageAccounts(); ``` -------------------------------- ### Configure CDN settings Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/configuration.md Sets parameters for private CDN distribution. ```javascript cloudinary.config({ private_cdn: true, secure_distribution: 'my-cdn.cloudfront.net', cdn_subdomain: true }); ``` -------------------------------- ### Project Directory Structure Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/README.md Displays the file organization of the Cloudinary Node.js SDK documentation repository. ```text output/ ├── README.md # This file ├── INDEX.md # Catalog of all symbols ├── MAIN_REFERENCE.md # Overview & navigation ├── configuration.md # Environment variables & config ├── types.md # Type definitions └── api-reference/ ├── config.md # Configuration methods ├── uploader.md # Upload operations ├── api.md # Admin API (resources, folders, etc) ├── url-generation.md # URL & HTML tag generation ├── search.md # Asset search API ├── utils.md # Signing, tokens, helpers ├── auth-and-analysis.md # Auth tokens & AI analysis ├── cache.md # URL caching system └── provisioning.md # Sub-account & user management ``` -------------------------------- ### Handle Configuration Errors in JavaScript Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/configuration.md Use a try-catch block to handle errors during configuration reloading or access. Check error messages to identify specific configuration issues. ```javascript try { cloudinary.config(true); // Reload from env const config = cloudinary.config(); console.log(`Connected to: ${config.cloud_name}`); } catch (error) { if (error.message.includes('Invalid CLOUDINARY_URL')) { console.error('Check CLOUDINARY_URL environment variable'); } process.exit(1); } ``` -------------------------------- ### Provision a cloud via HTTP API Source: https://github.com/cloudinary/cloudinary_npm/blob/master/docs/get-credentials.md Provision a cloud programmatically using a POST request to the Cloudinary provisioning endpoint. ```bash curl -X POST https://api.cloudinary.com/v1_1/provisioning/clouds \ -H "Content-Type: application/json" \ -d '{}' ``` -------------------------------- ### Check environment media limits Source: https://github.com/cloudinary/cloudinary_npm/blob/master/docs/upload-image.md Retrieves current product environment constraints to verify if an asset exceeds allowed size or pixel dimensions. ```js const { media_limits } = await cloudinary.api.usage(); console.log(media_limits.image_max_size_bytes); console.log(media_limits.video_max_size_bytes); console.log(media_limits.image_max_px, media_limits.asset_max_total_px); ``` -------------------------------- ### List all upload presets Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/api.md Retrieves a list of all configured upload presets for the account. ```javascript function upload_presets(options?: AdminApiOptions, callback?: ResponseCallback): Promise ``` ```javascript const cloudinary = require('cloudinary').v2; cloudinary.api.upload_presets().then(result => { result.presets.forEach(preset => { console.log(`${preset.name} (${preset.unsigned ? 'unsigned' : 'signed'})`); }); }).catch(error => { console.error('Failed:', error); }); ``` -------------------------------- ### Retrieve current configuration Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/configuration.md Access the entire configuration object or specific keys. ```javascript const config = cloudinary.config(); console.log(config.cloud_name); ``` ```javascript const apiKey = cloudinary.config('api_key'); ``` -------------------------------- ### Configure URL generation settings Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/configuration.md Sets parameters for URL construction, including HTTPS and CDN behavior. ```javascript cloudinary.config({ cloud_name: 'my-cloud', secure: true, // Use HTTPS (default: true) cdn_subdomain: true, // Use CDN subdomain secure_cdn_subdomain: true,// HTTPS CDN subdomain shorten: false, // Shorter URLs (default: false) force_version: false, // Add version to URL sign_url: false, // Sign generated URLs cname: 'cdn.example.com' // Custom domain }); ``` -------------------------------- ### create_sub_account() Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/provisioning.md Creates a new sub-account. Users with access to all sub-accounts automatically gain access to the new account. Cloud names must be globally unique. ```APIDOC ## create_sub_account(name, cloud_name, custom_attributes, enabled, base_account, options, callback) ### Description Creates a new sub-account. Cloud names must be globally unique across all Cloudinary accounts. ### Parameters - **name** (string) - Required - Display name for the sub-account - **cloud_name** (string) - Required - Unique cloud name (alphanumeric + underscore) - **custom_attributes** (object) - Optional - Custom key-value attributes - **enabled** (boolean) - Optional - Whether account is enabled - **base_account** (string) - Optional - ID of account to copy settings from - **options** (ProvisioningApiOptions) - Optional - API options - **callback** (ResponseCallback) - Optional - Optional Node-style callback ### Returns - **Promise** - New sub-account details ### Throws - Error if cloud_name is not unique across all Cloudinary accounts ``` -------------------------------- ### List assets with resources() Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/api.md Retrieves a list of assets with support for pagination and filtering by type or resource category. ```typescript function resources(options?: AdminAndResourceOptions, callback?: ResponseCallback): Promise ``` ```javascript const cloudinary = require('cloudinary').v2; cloudinary.api.resources({ max_results: 100, resource_type: 'image', type: 'upload' }).then(result => { result.resources.forEach(asset => { console.log(`${asset.public_id} (${asset.format})`); }); if (result.next_cursor) { console.log('More results available'); } }).catch(error => { console.error('Failed:', error); }); ``` -------------------------------- ### Implement Custom KeyValueCacheAdapter Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/cache.md Extends the base adapter class to integrate external key-value stores like Redis. ```javascript const cloudinary = require('cloudinary').v2; const KeyValueCacheAdapter = require('cloudinary/lib/cache/KeyValueCacheAdapter'); class RedisCache extends KeyValueCacheAdapter { constructor(redisClient) { super(); this.redis = redisClient; } get(key) { return this.redis.get(key); } set(key, value) { this.redis.set(key, value); return value; } delete(key) { this.redis.del(key); } flushAll() { this.redis.flushdb(); } } const redis = require('redis').createClient(); cloudinary.Cache.setAdapter(new RedisCache(redis)); ``` -------------------------------- ### Find assets by context with resources_by_context() Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/api.md Searches for assets matching specific metadata key-value pairs. ```typescript function resources_by_context(key: string, value?: string, options?: AdminAndResourceOptions, callback?: ResponseCallback): Promise ``` ```javascript const cloudinary = require('cloudinary').v2; cloudinary.api.resources_by_context('category', 'landscape').then(result => { console.log('Landscape images:', result.resources.length); }).catch(error => { console.error('Failed:', error); }); ``` -------------------------------- ### Generate video thumbnail Source: https://github.com/cloudinary/cloudinary_npm/blob/master/docs/transform-and-deliver-video.md Request an image format and specify a start_offset to capture a specific frame as a still image. ```javascript const posterUrl = cloudinary.url('examples/uploaded-large-video', { resource_type: 'video', format: 'jpg', start_offset: '2', // so_2 — two seconds in width: 400, crop: 'fill', secure: true }); // https://res.cloudinary.com//video/upload/c_fill,so_2,w_400/examples/uploaded-large-video.jpg ``` -------------------------------- ### create_archive() Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/uploader.md Creates a ZIP or TAR archive of specified assets. ```APIDOC ## create_archive(options, callback) ### Description Creates an archive (ZIP or TAR.GZ) containing specified assets, optionally async for large archives. ### Parameters - **options** (ArchiveApiOptions) - Optional - Archive creation options - **callback** (ResponseCallback) - Optional - Optional Node-style callback ### Return Type Promise - Resolves with archive response ### Example ```javascript const cloudinary = require('cloudinary').v2; cloudinary.uploader.create_archive({ public_ids: ['image1', 'image2', 'image3'], target_format: 'zip', target_public_id: 'my-archive' }).then(result => { console.log('Archive URL:', result.secure_url); }).catch(error => { console.error('Archive creation failed:', error); }); ``` ``` -------------------------------- ### root_folders(options, callback) Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/api.md Lists root-level folders in your account. ```APIDOC ## root_folders(options, callback) ### Description List root-level folders in your account. ### Parameters - **options** (AdminApiOptions) - Optional - Query options - **callback** (ResponseCallback) - Optional - Optional Node-style callback ### Return Type Promise - List of root folders ``` -------------------------------- ### getAdapter() Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/cache.md Retrieves the currently configured cache adapter. ```APIDOC ## getAdapter() ### Description Retrieve the currently configured cache adapter. ### Returns - **CacheAdapter | undefined** - The active cache adapter, or undefined if none set ``` -------------------------------- ### execute(options, callback) Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/search.md Executes the built search query against Cloudinary and returns the results. ```APIDOC ## execute(options?: AdminApiOptions, callback?: ResponseCallback) ### Description Executes the built search query and returns matching assets along with aggregation results and pagination info. ### Parameters - **options** (AdminApiOptions) - Optional - API options (oauth_token, etc.) - **callback** (ResponseCallback) - Optional - Optional Node-style callback ### Returns - **Promise** - Search results with assets and aggregations ``` -------------------------------- ### restore() Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/api.md Restores assets that were previously deleted. ```APIDOC ## restore(public_ids, options, callback) ### Description Restore (un-delete) deleted assets. ### Parameters - **public_ids** (string[]) - Required - Public IDs to restore - **options** (AdminApiOptions) - Optional - Restore options - **callback** (ResponseCallback) - Optional - Optional Node-style callback ### Return Type Promise - Restored asset metadata ``` -------------------------------- ### Configure static delivery Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/configuration.md Settings for optimizing asset delivery via CDN and custom domains. ```javascript cloudinary.config({ cloud_name: 'my-cloud', secure: true, cdn_subdomain: true, cname: 'assets.myapp.com' }); ``` -------------------------------- ### cloudinary.config Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/MAIN_REFERENCE.md Configures the Cloudinary SDK with your cloud credentials. ```APIDOC ## cloudinary.config ### Description Configures the SDK with cloud_name, api_key, and api_secret. ### Parameters - **config** (object) - Required - Object containing cloud_name, api_key, and api_secret. ``` -------------------------------- ### create_upload_preset() Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/api.md Creates a new upload preset. ```APIDOC ## create_upload_preset() ### Description Create a new upload preset. ### Signature `function create_upload_preset(options?: AdminApiOptions, callback?: ResponseCallback): Promise` ### Example ```javascript const cloudinary = require('cloudinary').v2; cloudinary.api.create_upload_preset({ name: 'my-preset', unsigned: true, folder: 'uploads' }).then(result => { console.log('Preset created'); }).catch(error => { console.error('Failed:', error); }); ``` ``` -------------------------------- ### Video with poster and custom source types Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/url-generation.md Configures specific source formats and applies transformations to the video poster image. ```javascript const cloudinary = require('cloudinary').v2; const html = cloudinary.video('my-video', { source_types: ['mp4', 'webm'], poster: { effect: 'sepia', quality: 'auto' }, controls: true, width: 640, height: 480 }); ``` -------------------------------- ### transformations() Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/api.md List all named transformations in your account. ```APIDOC ## transformations() ### Description List all named transformations in your account. ### Signature `function transformations(options?: AdminApiOptions, callback?: ResponseCallback): Promise` ### Example ```javascript const cloudinary = require('cloudinary').v2; cloudinary.api.transformations().then(result => { result.transformations.forEach(tx => { console.log(tx.name); }); }).catch(error => { console.error('Failed:', error); }); ``` ``` -------------------------------- ### Configure upload settings Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/configuration.md Sets parameters for file uploads, including proxy and chunking options. ```javascript cloudinary.config({ secure: true, api_proxy: 'https://my-proxy.example.com', chunk_size: 20000000 // 20MB chunks for large uploads }); ``` -------------------------------- ### Create a new upload preset Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/api.md Registers a new upload preset with the specified configuration options. ```javascript function create_upload_preset(options?: AdminApiOptions, callback?: ResponseCallback): Promise ``` ```javascript const cloudinary = require('cloudinary').v2; cloudinary.api.create_upload_preset({ name: 'my-preset', unsigned: true, folder: 'uploads' }).then(result => { console.log('Preset created'); }).catch(error => { console.error('Failed:', error); }); ``` -------------------------------- ### Retrieve account usage statistics Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/api.md Fetches storage, bandwidth, and transformation usage data. Defaults to today's date if no date is provided in options. ```javascript function usage(options?: AdminApiOptions, callback?: ResponseCallback): Promise ``` ```javascript const cloudinary = require('cloudinary').v2; cloudinary.api.usage().then(result => { console.log('Transformations:', result.transformations); console.log('Storage:', result.storage); console.log('Bandwidth:', result.bandwidth); }).catch(error => { console.error('Failed:', error); }); ``` -------------------------------- ### Import and Call Cloudinary Methods in JavaScript Source: https://github.com/cloudinary/cloudinary_npm/blob/master/docs/import-and-call.md Import the v2 module and call methods directly. Methods return a Promise when no callback is provided. ```js const cloudinary = require('cloudinary').v2; cloudinary.uploader.upload(...) cloudinary.api.resource(...) cloudinary.url(...) ``` -------------------------------- ### List root folders Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/api.md Retrieves a list of all root-level folders in the account. ```javascript function root_folders(options?: AdminApiOptions, callback?: ResponseCallback): Promise ``` ```javascript const cloudinary = require('cloudinary').v2; cloudinary.api.root_folders().then(result => { result.folders.forEach(folder => { console.log(folder.name); }); }).catch(error => { console.error('Failed:', error); }); ``` -------------------------------- ### Execute search query Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/search.md Performs the search request and returns a promise containing assets, aggregations, and pagination information. ```javascript const cloudinary = require('cloudinary').v2; cloudinary.search .expression('resource_type:image AND width > 1000') .max_results(100) .sort_by('created_at', 'desc') .aggregate('format') .with_field('colors') .execute() .then(result => { console.log(`Found ${result.total_count} images`); // Assets result.resources.forEach(asset => { console.log(`- ${asset.public_id}: ${asset.width}x${asset.height}`); }); // Aggregations console.log('Format distribution:', result.aggregations); // Pagination if (result.next_cursor) { console.log('More results available'); } }) .catch(error => { console.error('Search failed:', error); }); ``` -------------------------------- ### Client-side unsigned upload Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/uploader.md Shows how to perform an unsigned upload using a preset, suitable for client-side environments where the API secret should not be exposed. ```javascript const cloudinary = require('cloudinary').v2; cloudinary.uploader.unsigned_upload( fileBuffer, 'my-unsigned-preset', { public_id: 'user-upload-' + Date.now() } ).then(result => { console.log('Uploaded:', result.secure_url); }).catch(error => { console.error('Upload failed:', error.message); }); ``` -------------------------------- ### Retrieve asset metadata with resource() Source: https://github.com/cloudinary/cloudinary_npm/blob/master/_autodocs/api-reference/api.md Fetches detailed metadata for a specific asset. Requires the public ID and optional configuration for EXIF, colors, or face detection. ```typescript function resource(public_id: string, options?: AdminAndResourceOptions, callback?: ResponseCallback): Promise ``` ```javascript const cloudinary = require('cloudinary').v2; cloudinary.api.resource('my-image', { exif: true, colors: true, faces: true }).then(resource => { console.log(`Image: ${resource.width}x${resource.height}`); console.log(`Format: ${resource.format}`); console.log(`Predominant color: ${resource.colors[0]}`); }).catch(error => { console.error('Failed to get resource:', error); }); ```