OPEN-IMAGE-TINY,一個基于 Electron + VUE3 的圖片壓縮工具,項目開源地址:https://github.com/0604hx/open-image-tiny
功能描述
應用程序的命令行調用功能允許用戶通過終端(如Windows的CMD/PowerShell或Linux/macOS的Terminal)直接輸入命令與程序交互,無需圖形界面。
關于 commander
Commander 是 Node.js 最流行的命令行工具庫,用于快速構建 CLI 應用程序。它提供了聲明式語法、參數解析、幫助生成等特性,簡化命令行開發。
示例代碼:
const { program } = require('commander');program.name('my-cli').description('一個示例CLI工具').version('1.0.0');program.command('greet <name>').option('-c, --capitalize', '大寫輸出').action((name, options) => {let output = options.capitalize ? name.toUpperCase() : name;console.log(`Hello, ${output}!`);});program.parse(); // 解析命令行輸入
代碼實現
我們在 electron 應用啟動時,判斷命令行參數的個數,如果超過正常啟動的范圍,則視為命令行方式調用。
// electron/main.js
const handleCli = require('./cli')if(process.argv.length > (app.isPackaged?1:2)){(async ()=>{//處理命令行await handleCli()setTimeout(app.quit, 200)})();
}
else{//創建 GUI 窗口
}
// electron/cli.js
const pkg = require('../package.json')const { Command } = require("commander")
const pc = require('picocolors')
const { splitImageVertical, convertFormat } = require('./tool')const toInt = v=>parseInt(v)module.exports = async()=>{const cli = new Command()cli.command("convert <file>").alias("c").description(`轉換圖片格式(支持 ${pc.green("JPG/PNG/WEBP/AVIF")})`).option("-q, --quality [number]", "下載文件", toInt, 100 ).option("-t, --target [string]", "目標格式", "WebP").option("--resize [string]", "裁剪方式,width=按寬度、height=按高度").option("--resizeValue [number]", "裁剪大小/單位px", toInt).option("-r, --rotate [number]", "旋轉角度", toInt).action(async (/**@type {String} */file, /**@type {import('./tool').ConvertConfig} */ps)=>{await convertFormat(file, null, ps)})cli.command("split <file>").alias("s").description("垂直切割圖片").option("-h, --height [number]", "切割高度/單位px", toInt, 1000).option("-f, --fit [boolean]", "高度不足時自動填充", true).option("-c, --color [string]", "填充高度", "#ffffff").action(async (/**@type {String} */file, /**@type {import('./tool').SplitConfig} */ps)=>{await splitImageVertical(file, ps)})cli.name(pkg.name).description(pkg.description).version(pkg.version).parseAsync().catch(e=>console.error(`${pc.red("命令行執行出錯:")}${e}`))
}