### PicGo CLI Usage Examples Source: https://context7.com/picgo/picgo-core-doc/llms.txt Provides examples of using the PicGo command-line interface for various tasks. This includes installing PicGo globally, uploading images from paths or clipboard, configuring uploaders interactively or specifically, installing, updating, and uninstalling plugins, changing the language, and using custom configurations or debug/silent modes. ```bash # Install globally npm install picgo -g # Upload specific images picgo upload /home/user/image1.jpg /home/user/image2.png # Output: # [PicGo SUCCESS]: # https://i.loli.net/2024/12/03/abc123.jpg # https://i.loli.net/2024/12/03/def456.png # Upload from clipboard picgo upload # Configure uploader (interactive) picgo set uploader # ? Choose a(n) uploader # smms # ❯ github # qiniu # imgur # Configure specific uploader picgo set uploader github # ? repo: username/repo # ? token: ghp_yourToken # ? path: images/ # ? customUrl: https://cdn.jsdelivr.net/gh/username/repo # ? branch: main # Choose current uploader picgo use uploader # ? Use an uploader # ❯ github # smms # qiniu # Install plugins picgo install watermark compress # Update plugins picgo update watermark # Uninstall plugins picgo uninstall compress # Change language picgo i18n en # Use custom config file picgo -c /path/to/config.json upload image.jpg # Debug mode picgo -d upload image.jpg # Silent mode picgo -s upload image.jpg # Check version picgo -v ``` -------------------------------- ### Install, Update, and Uninstall PicGo Plugins with npm Source: https://context7.com/picgo/picgo-core-doc/llms.txt Programmatically manage PicGo plugins using the pluginHandler. This allows for installation, updating, and uninstallation of plugins following the 'picgo-plugin-" convention. It supports short names, full names, and scoped packages, and emits events for success and failure. ```javascript const { PicGo } = require('picgo') const picgo = new PicGo() // Listen for installation events picgo.on('installSuccess', plugins => { console.log('Successfully installed:', plugins) }) picgo.on('installFailed', error => { console.error('Installation failed:', error) }) // Install plugins (can use short name or full name) const installPlugins = async () => { const result = await picgo.pluginHandler.install(['watermark', 'compress']) if (result.success) { console.log('Installed plugins:', result.body) // ['picgo-plugin-watermark', 'picgo-plugin-compress'] } else { console.error('Installation error:', result.body) } } // Update plugins const updatePlugins = async () => { const result = await picgo.pluginHandler.update(['watermark']) console.log('Update result:', result.success ? 'Success' : 'Failed') } // Uninstall plugins const uninstallPlugins = async () => { const result = await picgo.pluginHandler.uninstall(['compress']) console.log('Uninstall result:', result.success ? 'Success' : 'Failed') } // Install scoped plugin const installScopedPlugin = async () => { const result = await picgo.pluginHandler.install(['@username/picgo-plugin-custom']) console.log('Scoped plugin installed:', result.success) } installPlugins() ``` -------------------------------- ### Internationalization (i18n) with PicGo Source: https://context7.com/picgo/picgo-core-doc/llms.txt Explains how to add language support and translate text within PicGo plugins and custom implementations. It covers getting available languages, setting the current language, adding new translations, and translating text with or without parameters. New languages can also be added. ```javascript const { PicGo } = require('picgo') const picgo = new PicGo() // Get available languages const languages = picgo.i18n.getLanguageList() console.log('Available languages:', languages) // ['zh-CN', 'zh-TW', 'en'] // Set language picgo.i18n.setLanguage('en') // Add translations to existing language picgo.i18n.addLocale('en', { 'UPLOAD_SUCCESS': 'Image uploaded successfully', 'UPLOAD_FAILED': 'Upload failed: ${error}', 'CURRENT_UPLOADER': 'Current uploader is ${name}' }) // Translate text const successMsg = picgo.i18n.translate('UPLOAD_SUCCESS') console.log(successMsg) // 'Image uploaded successfully' // Translate with parameters const uploaderMsg = picgo.i18n.translate('CURRENT_UPLOADER', { name: 'GitHub' }) console.log(uploaderMsg) // 'Current uploader is GitHub' // Add a new language picgo.i18n.addLanguage('ja', { 'UPLOAD_SUCCESS': 'アップロード成功', 'UPLOAD_FAILED': 'アップロード失敗: ${error}', 'CURRENT_UPLOADER': '現在のアップローダーは${name}です' }) picgo.i18n.setLanguage('ja') const japaneseMsg = picgo.i18n.translate('UPLOAD_SUCCESS') console.log(japaneseMsg) // 'アップロード成功' ``` -------------------------------- ### Make HTTP Requests with Proxy Support using PicGo Source: https://context7.com/picgo/picgo-core-doc/llms.txt Utilize PicGo's built-in request module to make HTTP requests (GET, POST, etc.) that automatically honor user-configured proxy settings. This module is based on axios and supports options like 'resolveWithFullResponse' and 'responseType'. ```javascript const { PicGo } = require('picgo') const picgo = new PicGo() // Configure proxy in config picgo.saveConfig({ 'picBed.proxy': 'http://127.0.0.1:7890' }) // Make POST request with full response const uploadToCustomService = async () => { const opt = { method: 'post', url: 'https://api.example.com/upload', data: { image: 'base64data...' }, resolveWithFullResponse: true } try { const response = await picgo.request(opt) console.log('Status:', response.status) console.log('Data:', response.data) } catch (error) { console.error('Request failed:', error) } } // Make GET request with arraybuffer response const downloadImage = async () => { const opt = { method: 'get', url: 'https://example.com/image.jpg', responseType: 'arraybuffer', resolveWithFullResponse: true } const response = await picgo.request(opt) console.log('Buffer length:', response.data.length) // response.data is a Buffer } // Simple request (returns only data) const simpleRequest = async () => { const data = await picgo.request({ method: 'get', url: 'https://api.example.com/data' }) console.log(data) // Direct access to response.data } uploadToCustomService() ``` -------------------------------- ### Initialize PicGo Instance Source: https://context7.com/picgo/picgo-core-doc/llms.txt Initialize a PicGo instance to use the core upload functionality. You can use the default configuration file or specify a custom path. ```APIDOC ## Initialize PicGo Instance ### Description Initialize a PicGo instance to use the core upload functionality. You can use the default configuration file or specify a custom path. The default configuration is located at `~/.picgo/config.json` on Linux/macOS and `C:\Users\username\.picgo\config.json` on Windows. ### Method Constructor ### Endpoint N/A ### Parameters #### Path Parameters * **configPath** (string) - Optional - The path to a custom configuration file. ### Request Example ```javascript // v1.5.0+ with ES6 modules import { PicGo } from 'picgo' // Using default config (~/.picgo/config.json) const picgo = new PicGo() // Using custom config file const picgoCustom = new PicGo('/path/to/custom/config.json') // v1.4.x and earlier (CommonJS) const PicGo = require('picgo') const picgoLegacy = new PicGo() ``` ### Response #### Success Response (200) * **picgoInstance** (object) - An instance of the PicGo core. #### Response Example N/A ``` -------------------------------- ### Initialize PicGo Instance (JavaScript) Source: https://context7.com/picgo/picgo-core-doc/llms.txt Initializes a PicGo instance for image upload functionality. It can use the default configuration file located at '~/.picgo/config.json' (Linux/macOS) or 'C:\Users\username\.picgo\config.json' (Windows), or a custom configuration file path. Supports both ES6 modules and CommonJS syntax. ```javascript import { PicGo } from 'picgo' // Using default config (~/.picgo/config.json) const picgo = new PicGo() // Using custom config file const picgoCustom = new PicGo('/path/to/custom/config.json') // v1.4.x and earlier (CommonJS) const PicGo = require('picgo') const picgoLegacy = new PicGo() ``` -------------------------------- ### Register Custom Uploader with PicGo Source: https://context7.com/picgo/picgo-core-doc/llms.txt Demonstrates how to create and register a custom uploader for additional image hosting services. The uploader must implement a `handle` method for uploading images and a `config` method for CLI configuration. It takes an array of image objects as input and adds `imgUrl` to each output object upon successful upload. Error handling and notifications are included. ```javascript const { PicGo } = require('picgo') const picgo = new PicGo() // Register custom uploader picgo.helper.uploader.register('custom-uploader', { handle: async ctx => { const output = ctx.output for (let i = 0; i < output.length; i++) { const img = output[i] try { // Custom upload logic const response = await ctx.request({ method: 'POST', url: 'https://your-image-service.com/upload', data: { image: img.base64Image, filename: img.fileName } }) // Add imgUrl to output output[i].imgUrl = response.url output[i].url = response.url picgo.log.success(`Uploaded: ${img.fileName}`) } catch (error) { picgo.log.error(`Failed to upload ${img.fileName}: ${error.message}`) // Send notification on failure ctx.emit('notification', { title: 'Upload Failed', body: `Could not upload ${img.fileName}`, text: 'https://your-image-service.com/docs/errors' }) throw error } } return ctx }, // Optional: config method for CLI configuration config: ctx => { return [ { type: 'input', name: 'apiKey', message: 'API Key', default: ctx.getConfig('picBed.custom-uploader.apiKey') || '' }, { type: 'input', name: 'endpoint', message: 'Upload Endpoint', default: ctx.getConfig('picBed.custom-uploader.endpoint') || '' } ] } }) // Configure the custom uploader picgo.saveConfig({ 'picBed.uploader': 'custom-uploader', 'picBed.custom-uploader': { apiKey: 'your-api-key', endpoint: 'https://your-image-service.com/upload' } }) // Upload using custom uploader picgo.upload(['/home/user/photo.jpg']) ``` -------------------------------- ### Configure Image Hosting Service (JavaScript) Source: https://context7.com/picgo/picgo-core-doc/llms.txt Manages PicGo configuration for uploaders, transformers, and plugins. `setConfig` applies temporary changes within the current session, while `saveConfig` persists changes to the configuration file. Configuration values can also be retrieved using `getConfig`. ```javascript const { PicGo } = require('picgo') const picgo = new PicGo() // Set config temporarily (not saved to file) picgo.setConfig({ 'picBed.current': 'github', 'picBed.uploader': 'github' }) // Save config permanently to file picgo.saveConfig({ 'picBed.github': { repo: 'username/repo', token: 'ghp_yourGithubTokenHere', path: 'images/', customUrl: 'https://cdn.jsdelivr.net/gh/username/repo', branch: 'main' }, 'picBed.uploader': 'github' }) // Get config values const currentUploader = picgo.getConfig('picBed.uploader') console.log('Current uploader:', currentUploader) // 'github' const fullConfig = picgo.getConfig() console.log('Full config:', JSON.stringify(fullConfig, null, 2)) ``` -------------------------------- ### Configure Image Hosting Service Source: https://context7.com/picgo/picgo-core-doc/llms.txt Set or save configuration for PicGo modules including uploaders, transformers, and plugins. Use `setConfig` for temporary context changes or `saveConfig` to persist to the configuration file. ```APIDOC ## Configure Image Hosting Service ### Description Set or save configuration for PicGo modules including uploaders, transformers, and plugins. Use `setConfig` for temporary context changes or `saveConfig` to persist to the configuration file. ### Method `setConfig`, `saveConfig`, `getConfig` ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const { PicGo } = require('picgo') const picgo = new PicGo() // Set config temporarily (not saved to file) picgo.setConfig({ 'picBed.current': 'github', 'picBed.uploader': 'github' }) // Save config permanently to file picgo.saveConfig({ 'picBed.github': { repo: 'username/repo', token: 'ghp_yourGithubTokenHere', path: 'images/', customUrl: 'https://cdn.jsdelivr.net/gh/username/repo', branch: 'main' }, 'picBed.uploader': 'github' }) // Get config values const currentUploader = picgo.getConfig('picBed.uploader') console.log('Current uploader:', currentUploader) // 'github' const fullConfig = picgo.getConfig() console.log('Full config:', JSON.stringify(fullConfig, null, 2)) ``` ### Response #### Success Response (200) * **setConfig**: Returns `undefined`. * **saveConfig**: Returns `undefined`. * **getConfig**: Returns the configuration object or a specific configuration value. #### Response Example ```json // For getConfig('picBed.uploader') "github" // For getConfig() { "picBed": { "current": "github", "uploader": "github", "github": { "repo": "username/repo", "token": "ghp_yourGithubTokenHere", "path": "images/", "customUrl": "https://cdn.jsdelivr.net/gh/username/repo", "branch": "main" } } } ``` ``` -------------------------------- ### Upload Images Source: https://context7.com/picgo/picgo-core-doc/llms.txt Upload one or multiple images to the configured image hosting service. The upload function accepts an array of file paths or uploads from clipboard if no argument is provided. Returns a Promise with the uploaded image URLs. ```APIDOC ## Upload Images ### Description Upload one or multiple images to the configured image hosting service. The upload function accepts an array of file paths or uploads from clipboard if no argument is provided. Returns a Promise with the uploaded image URLs. ### Method `upload` ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Takes file paths or clipboard content as arguments) ### Request Example ```javascript const { PicGo } = require('picgo') const picgo = new PicGo() // Upload specific image files const uploadFiles = async () => { try { const result = await picgo.upload(['/home/user/image1.jpg', '/home/user/image2.png']) console.log(result) // Output: ['https://i.loli.net/2024/12/03/abc123.jpg', 'https://i.loli.net/2024/12/03/def456.png'] } catch (error) { console.error('Upload failed:', error) } } // Upload from clipboard (will convert to PNG) const uploadFromClipboard = async () => { const result = await picgo.upload() console.log('Uploaded from clipboard:', result[0]) } uploadFiles() ``` ### Response #### Success Response (200) * **uploadedUrls** (array) - An array of strings, where each string is the URL of an uploaded image. #### Response Example ```json [ "https://i.loli.net/2024/12/03/abc123.jpg", "https://i.loli.net/2024/12/03/def456.png" ] ``` ``` -------------------------------- ### Register Lifecycle Plugins with PicGo Source: https://context7.com/picgo/picgo-core-doc/llms.txt Extend PicGo's functionality by registering custom plugins that hook into specific stages of the upload lifecycle, such as before transformation, before upload, and after upload. Each plugin requires a 'handle' method to execute custom logic. ```javascript const { PicGo } = require('picgo') const picgo = new PicGo() // Register beforeTransform plugin to add watermark picgo.helper.beforeTransformPlugins.register('watermark', { handle: ctx => { console.log('Adding watermark to images...') // Custom watermark logic here return ctx } }) // Register beforeUpload plugin to compress images picgo.helper.beforeUploadPlugins.register('compress', { handle: ctx => { console.log('Compressing images before upload...') ctx.output = ctx.output.map(img => { // Compression logic would modify img.base64Image console.log(`Compressing ${img.fileName}`) return img }) return ctx } }) // Register afterUpload plugin to save URLs to database picgo.helper.afterUploadPlugins.register('save-to-db', { handle: async ctx => { for (const img of ctx.output) { console.log(`Saving URL to database: ${img.imgUrl}`) // await saveToDatabase(img) } return ctx } }) // Plugins must be registered before upload picgo.upload(['/home/user/image.jpg']) ``` -------------------------------- ### PicGo Logging System (JavaScript) Source: https://context7.com/picgo/picgo-core-doc/llms.txt Demonstrates how to use the built-in logging system in PicGo-Core to output informational, success, warning, and error messages. Logs are persisted to 'picgo.log' and displayed in the console. This is useful for tracking upload processes and debugging. ```javascript const { PicGo } = require('picgo') const picgo = new PicGo() // Info message (blue) picgo.log.info('Starting upload process') // Success message (green) picgo.log.success('Upload completed successfully') // Warning message (yellow) picgo.log.warn('Configuration not optimized') // Error message (red) try { throw new Error('Network connection failed') } catch (error) { picgo.log.error(error) } // Example upload with logging const uploadWithLogging = async () => { picgo.log.info('Initializing upload...') try { const result = await picgo.upload(['/home/user/photo.jpg']) picgo.log.success(`Image uploaded: ${result[0]}`) } catch (error) { picgo.log.error(`Upload failed: ${error.message}`) } } uploadWithLogging() // Log output appears both in console and in ~/.picgo/picgo.log: // 2024-12-03 10:30:15 [PicGo INFO] Initializing upload... // 2024-12-03 10:30:18 [PicGo SUCCESS] Image uploaded: https://i.loli.net/2024/12/03/abc123.jpg ``` -------------------------------- ### Dynamically Load and Unload PicGo Plugins at Runtime Source: https://context7.com/picgo/picgo-core-doc/llms.txt Manually load and unload plugins at runtime without npm. This method is useful for integrating third-party plugins or managing plugin lifecycles within an application. It supports registering, checking, retrieving, and unregistering plugins using `pluginLoader` or the `use()` method for direct integration. ```javascript const { PicGo } = require('picgo') const picgo = new PicGo() // Method 1: Using pluginLoader (for manual control) const customPlugin = require('picgo-plugin-custom') // Register plugin picgo.pluginLoader.registerPlugin('custom', customPlugin) // Check if plugin exists if (picgo.pluginLoader.hasPlugin('custom')) { console.log('Plugin registered successfully') } // Get plugin instance const plugin = picgo.pluginLoader.getPlugin('custom') console.log('Plugin:', plugin) // Unregister plugin picgo.pluginLoader.unregisterPlugin('custom') // Method 2: Using use() method (v1.5.0+) const PluginMigrater = require('picgo-plugin-pic-migrater') const MinioUploader = require('picgo-plugin-minio') // Load without registering (for direct method calls) const migrater = picgo.use(PluginMigrater) // Load and register (becomes available as uploader) picgo.use(MinioUploader, 'minio') // Configure plugins picgo.setConfig({ 'picgo-plugin-pic-migrater': { newFileSuffix: '_new', include: '', exclude: '' }, picBed: { current: 'minio', uploader: 'minio', minio: { endpoint: 'http://localhost:9000', accessKey: 'minioadmin', secretKey: 'minioadmin', bucket: 'picgo', path: 'uploads/', useSSL: false } } }) // Use plugin methods directly const migrationResult = migrater.migrateFiles(['/docs/readme.md']) console.log(`Migrated ${migrationResult.success} of ${migrationResult.total} files`) ``` -------------------------------- ### Listen to Upload Events with PicGo Source: https://context7.com/picgo/picgo-core-doc/llms.txt Monitor the upload lifecycle by subscribing to various events such as upload progress, before and after transformations, successful uploads, and failures. These events provide insights into the upload process and allow for custom handling. ```javascript const { PicGo } = require('picgo') const picgo = new PicGo() // Track upload progress picgo.on('uploadProgress', progress => { console.log(`Upload progress: ${progress}%`) // Values: 0, 30, 60, 100 (success), -1 (failed) }) // Before transformation picgo.on('beforeTransform', ctx => { console.log('Input files:', ctx.input) // ['/home/user/image.jpg'] }) // Before upload (after transformation) picgo.on('beforeUpload', ctx => { console.log('Transformed output:', ctx.output) // [{ base64Image, fileName, width, height, extname }] }) // After successful upload picgo.on('afterUpload', ctx => { console.log('Upload successful:', ctx.output) // [{ fileName, width, height, extname, imgUrl: 'https://...' }] }) // Upload finished (after all plugins) picgo.on('finished', ctx => { const urls = ctx.output.map(img => img.imgUrl) console.log('All uploads complete:', urls) }) // Handle upload failures picgo.on('failed', error => { console.error('Upload failed:', error.message) }) // Notification events picgo.on('notification', notice => { console.log(`${notice.title}: ${notice.body}`) if (notice.text) console.log('More info:', notice.text) }) // Perform upload picgo.upload(['/home/user/photo.jpg']) ``` -------------------------------- ### Upload Images via PicGo API (JavaScript) Source: https://context7.com/picgo/picgo-core-doc/llms.txt Uploads one or multiple image files to the configured image hosting service using the PicGo API. The function accepts an array of file paths or uploads from the clipboard if no arguments are provided. It returns a Promise that resolves with an array of uploaded image URLs. Error handling for upload failures is included. ```javascript const { PicGo } = require('picgo') const picgo = new PicGo() // Upload specific image files const uploadFiles = async () => { try { const result = await picgo.upload(['/home/user/image1.jpg', '/home/user/image2.png']) console.log(result) // Output: ['https://i.loli.net/2024/12/03/abc123.jpg', 'https://i.loli.net/2024/12/03/def456.png'] } catch (error) { console.error('Upload failed:', error) } } // Upload from clipboard (will convert to PNG) const uploadFromClipboard = async () => { const result = await picgo.upload() console.log('Uploaded from clipboard:', result[0]) } uploadFiles() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.