西安網站建設網絡企業(yè)做網站維護
鶴壁市浩天電氣有限公司
2026/01/24 08:55:21
西安網站建設網絡,企業(yè)做網站維護,做什麼網站有前景,offic做網站的軟件前言對于前端開發(fā)者而言#xff0c;Electron 與鴻蒙 OS 的組合#xff0c;是低成本切入鴻蒙生態(tài)的最優(yōu)解之一。無需學習 ArkTS 原生開發(fā)#xff0c;僅憑 HTML/CSS/JS 技術棧#xff0c;就能開發(fā)出適配鴻蒙設備的桌面應用。前面的文章已經講解了基礎開發(fā)流程和進階功能…前言對于前端開發(fā)者而言Electron 與鴻蒙 OS 的組合是低成本切入鴻蒙生態(tài)的最優(yōu)解之一。無需學習 ArkTS 原生開發(fā)僅憑 HTML/CSS/JS 技術棧就能開發(fā)出適配鴻蒙設備的桌面應用。前面的文章已經講解了基礎開發(fā)流程和進階功能本文將聚焦實用性開發(fā)一個 “鴻蒙系統(tǒng)工具箱”集成設備信息查詢、文件快速搜索、系統(tǒng)命令執(zhí)行三大核心功能。全程提供可直接運行的代碼幫助開發(fā)者快速打造一款實用的鴻蒙桌面工具。一、功能定位與核心優(yōu)勢1. 工具功能清單功能模塊核心能力鴻蒙適配要點設備信息查詢查看 CPU、內存、系統(tǒng)版本、磁盤占用等調用 Node.js 系統(tǒng)模塊適配鴻蒙設備目錄結構文件快速搜索根據文件名關鍵詞搜索鴻蒙設備內文件遍歷鴻蒙設備文件系統(tǒng)優(yōu)化搜索算法提升效率系統(tǒng)命令執(zhí)行執(zhí)行l(wèi)s、pwd、top等 Linux 命令適配鴻蒙 Linux 兼容層支持命令結果實時輸出2. 核心優(yōu)勢輕量化無冗余依賴打包后體積小運行內存占用低實用性功能貼合鴻蒙設備日常使用需求易擴展模塊化代碼結構可快速添加新功能如進程管理、網絡測速。二、環(huán)境搭建沿用基礎開發(fā)環(huán)境無需額外配置鴻蒙 OS 3.0 設備開啟開發(fā)者模式、Linux 兼容層Node.js 16.x LTS Electron 22.x electron-packagerVS Code安裝 Electron 插件提升開發(fā)效率。安裝核心依賴bash運行# 初始化項目 mkdir harmony-electron-toolbox cd harmony-electron-toolbox npm init -y # 安裝核心依賴 npm install electron22.3.2 --save npm install nodemon --save-dev # 熱重載開發(fā)依賴修改package.json配置腳本json{ name: harmony-electron-toolbox, version: 1.0.0, main: main.js, scripts: { start: nodemon --exec electron ., package: electron-packager . harmony-toolbox --platformlinux --archx64 --outdist }, devDependencies: { nodemon: ^3.1.0 }, dependencies: { electron: ^22.3.2 } }三、核心代碼實現(xiàn)1. 項目結構plaintextharmony-electron-toolbox/ ├── main.js # 主進程功能邏輯IPC通信 ├── preload.js # 通信橋接暴露安全API ├── index.html # 渲染進程UI界面交互 └── package.json # 項目配置2. 主進程main.js主進程是工具的核心負責文件搜索、命令執(zhí)行、系統(tǒng)信息查詢并通過 IPC 與渲染進程通信。javascript運行const { app, BrowserWindow, ipcMain } require(electron); const path require(path); const fs require(fs); const { exec } require(child_process); const os require(os); let mainWindow; // 創(chuàng)建應用窗口 function createWindow() { mainWindow new BrowserWindow({ width: 1000, height: 700, title: 鴻蒙系統(tǒng)工具箱, webPreferences: { nodeIntegration: true, contextIsolation: false, // 鴻蒙兼容必需配置 preload: path.join(__dirname, preload.js) }, frame: false, // 鴻蒙扁平化窗口樣式 titleBarStyle: hidden }); mainWindow.loadFile(index.html); mainWindow.webContents.openDevTools(); // 調試用發(fā)布時關閉 // 窗口關閉事件 mainWindow.on(closed, () { mainWindow null; }); } // 功能1獲取設備信息 ipcMain.on(get-device-info, (event) { try { const deviceInfo { 系統(tǒng)版本: os.version(), 主機名: os.hostname(), CPU核心數: os.cpus().length, CPU型號: os.cpus()[0].model, 總內存: (os.totalmem() / 1024 / 1024 / 1024).toFixed(2) GB, 空閑內存: (os.freemem() / 1024 / 1024 / 1024).toFixed(2) GB, 磁盤根目錄占用: getDiskUsage(/) }; event.reply(device-info-reply, { success: true, data: deviceInfo }); } catch (error) { event.reply(device-info-reply, { success: false, message: error.message }); } }); // 輔助函數獲取磁盤占用 function getDiskUsage(dir) { try { const stats fs.statfs(dir); const total (stats.blocks * stats.blockSize) / 1024 / 1024 / 1024; const free (stats.bfree * stats.blockSize) / 1024 / 1024 / 1024; const used (total - free).toFixed(2) GB / total.toFixed(2) GB; return used; } catch (error) { return 獲取失敗; } } // 功能2文件快速搜索 ipcMain.on(search-files, (event, keyword) { if (!keyword) { event.reply(search-files-reply, { success: false, message: 請輸入搜索關鍵詞 }); return; } const results []; // 搜索鴻蒙設備常用目錄用戶目錄 根目錄 const searchDirs [os.homedir(), /]; searchDirs.forEach(dir { try { searchDir(dir, keyword, results); } catch (error) { // 忽略無權限目錄 } }); event.reply(search-files-reply, { success: true, data: results.slice(0, 50) }); // 限制最多返回50條 }); // 遞歸搜索目錄 function searchDir(dir, keyword, results) { const files fs.readdirSync(dir, { withFileTypes: true }); for (const file of files) { const fullPath path.join(dir, file.name); // 文件名包含關鍵詞則加入結果 if (file.name.toLowerCase().includes(keyword.toLowerCase())) { results.push({ name: file.name, path: fullPath, type: file.isDirectory() ? 文件夾 : 文件 }); } // 遞歸搜索子文件夾 if (file.isDirectory()) { try { searchDir(fullPath, keyword, results); } catch (error) { continue; } } } } // 功能3執(zhí)行系統(tǒng)命令 ipcMain.on(exec-command, (event, cmd) { if (!cmd) { event.reply(command-output, 請輸入要執(zhí)行的命令); return; } // 執(zhí)行Linux命令適配鴻蒙Linux兼容層 exec(cmd, { maxBuffer: 1024 * 1024 }, (error, stdout, stderr) { if (error) { event.reply(command-output, 執(zhí)行失敗${error.message}); return; } if (stderr) { event.reply(command-output, 錯誤輸出${stderr}); return; } event.reply(command-output, 執(zhí)行結果
${stdout}); }); }); // 窗口控制 ipcMain.on(window-control, (event, action) { switch (action) { case minimize: mainWindow.minimize(); break; case close: mainWindow.close(); break; } }); // 應用啟動 app.whenReady().then(createWindow); app.on(window-all-closed, () { if (process.platform ! darwin) app.quit(); }); app.on(activate, () { if (BrowserWindow.getAllWindows().length 0) createWindow(); });3. 預加載腳本preload.js作為渲染進程與主進程的安全通信橋梁暴露核心功能 API。javascript運行const { ipcRenderer, contextBridge } require(electron); contextBridge.exposeInMainWorld(toolboxAPI, { // 獲取設備信息 getDeviceInfo: () { return new Promise((resolve) { ipcRenderer.send(get-device-info); ipcRenderer.once(device-info-reply, (event, data) { resolve(data); }); }); }, // 搜索文件 searchFiles: (keyword) { return new Promise((resolve) { ipcRenderer.send(search-files, keyword); ipcRenderer.once(search-files-reply, (event, data) { resolve(data); }); }); }, // 執(zhí)行系統(tǒng)命令 execCommand: (cmd) { ipcRenderer.send(exec-command, cmd); }, // 監(jiān)聽命令輸出 onCommandOutput: (callback) { ipcRenderer.on(command-output, (event, data) { callback(data); }); }, // 窗口控制 windowControl: (action) { ipcRenderer.send(window-control, action); } });4. 渲染進程index.html采用鴻蒙扁平化設計風格實現(xiàn)三大功能的 UI 與交互邏輯。html預覽!DOCTYPE html html langzh-CN head meta charsetUTF-8 meta nameviewport contentwidthdevice-width, initial-scale1.0 title鴻蒙系統(tǒng)工具箱/title style * { margin: 0; padding: 0; box-sizing: border-box; font-family: HarmonyOS Sans SC, sans-serif; } body { background-color: #f5f5f7; color: #1d1d1f; } /* 鴻蒙風格標題欄 */ .title-bar { display: flex; justify-content: space-between; align-items: center; padding: 12px 20px; background-color: #fff; border-bottom: 1px solid #e5e5e7; } .title { font-size: 18px; font-weight: 500; } .control-btns button { width: 32px; height: 32px; border: none; background: transparent; border-radius: 50%; cursor: pointer; font-size: 16px; margin-left: 8px; } .control-btns button:hover { background-color: #f0f0f2; } /* 功能標簽頁 */ .tabs { display: flex; background-color: #fff; border-bottom: 1px solid #e5e5e7; } .tab-btn { padding: 12px 24px; border: none; background: transparent; font-size: 16px; cursor: pointer; position: relative; } .tab-btn.active { color: #007aff; } .tab-btn.active::after { content: ; position: absolute; bottom: -1px; left: 0; width: 100%; height: 2px; background-color: #007aff; } /* 功能內容區(qū) */ .content { padding: 20px; height: calc(100vh - 110px); overflow-y: auto; } .tab-content { display: none; } .tab-content.active { display: block; } /* 通用樣式卡片、輸入框、按鈕 */ .card { background-color: #fff; border-radius: 12px; padding: 20px; margin-bottom: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); } .input-box { width: 100%; padding: 12px 16px; border: 1px solid #e5e5e7; border-radius: 8px; font-size: 16px; margin-bottom: 16px; outline: none; } .input-box:focus { border-color: #007aff; } .btn { padding: 12px 24px; background-color: #007aff; color: #fff; border: none; border-radius: 8px; font-size: 16px; cursor: pointer; } .btn:hover { background-color: #0066cc; } /* 設備信息樣式 */ .info-list { display: grid; grid-template-columns: repeat(2, 1fr); gap: 16px; } .info-item { padding: 12px; background-color: #f5f5f7; border-radius: 8px; } .info-label { font-size: 14px; color: #86868b; margin-bottom: 4px; } .info-value { font-size: 16px; font-weight: 500; } /* 文件搜索結果樣式 */ .search-result { margin-top: 16px; max-height: 400px; overflow-y: auto; } .result-item { padding: 12px; border-bottom: 1px solid #e5e5e7; display: flex; justify-content: space-between; } .result-item:last-child { border-bottom: none; } .result-path { font-size: 14px; color: #86868b; } /* 命令執(zhí)行樣式 */ .command-output { width: 100%; height: 400px; padding: 16px; border: 1px solid #e5e5e7; border-radius: 8px; background-color: #f5f5f7; font-family: monospace; font-size: 14px; white-space: pre-wrap; overflow-y: auto; } /style /head body !-- 標題欄 -- div classtitle-bar div classtitle鴻蒙系統(tǒng)工具箱/div div classcontrol-btns button onclickwindow.toolboxAPI.windowControl(minimize)—/button button onclickwindow.toolboxAPI.windowControl(close)?/button /div /div !-- 功能標簽頁 -- div classtabs button classtab-btn active onclickswitchTab(device-info)設備信息/button button classtab-btn onclickswitchTab(file-search)文件搜索/button button classtab-btn onclickswitchTab(command-exec)命令執(zhí)行/button /div !-- 功能內容區(qū) -- div classcontent !-- 設備信息面板 -- div classtab-content active iddevice-info div classcard h3 stylemargin-bottom: 16px;設備基礎信息/h3 div classinfo-list iddevice-info-list div classinfo-item div classinfo-label加載中.../div /div /div /div /div !-- 文件搜索面板 -- div classtab-content idfile-search div classcard input typetext classinput-box idsearch-keyword placeholder請輸入要搜索的文件名關鍵詞... button classbtn onclicksearchFiles()開始搜索/button div classsearch-result idsearch-result/div /div /div !-- 命令執(zhí)行面板 -- div classtab-content idcommand-exec div classcard input typetext classinput-box idcommand-input placeholder請輸入Linux命令如ls、pwd、top -n 1... button classbtn onclickexecCommand()執(zhí)行命令/button div classcommand-output idcommand-output請輸入命令并執(zhí)行.../div /div /div /div script // 頁面加載初始化 window.addEventListener(DOMContentLoaded, () { loadDeviceInfo(); // 監(jiān)聽命令輸出 window.toolboxAPI.onCommandOutput((output) { document.getElementById(command-output).textContent output; }); }); // 切換標簽頁 function switchTab(tabId) { // 切換標簽按鈕狀態(tài) document.querySelectorAll(.tab-btn).forEach(btn { btn.classList.remove(active); if (btn.onclick.toString().includes(tabId)) { btn.classList.add(active); } }); // 切換內容面板狀態(tài) document.querySelectorAll(.tab-content).forEach(panel { panel.classList.remove(active); }); document.getElementById(tabId).classList.add(active); } // 加載設備信息 async function loadDeviceInfo() { const result await window.toolboxAPI.getDeviceInfo(); const listEl document.getElementById(device-info-list); if (!result.success) { listEl.innerHTML div classinfo-itemdiv classinfo-value${result.message}/div/div; return; } let html ; for (const [key, value] of Object.entries(result.data)) { html div classinfo-item div classinfo-label${key}/div div classinfo-value${value}/div /div ; } listEl.innerHTML html; } // 搜索文件 async function searchFiles() { const keyword document.getElementById(search-keyword).value.trim(); const resultEl document.getElementById(search-result); resultEl.innerHTML div stylepadding: 12px; text-align: center;搜索中.../div; const result await window.toolboxAPI.searchFiles(keyword); if (!result.success) { resultEl.innerHTML div stylepadding: 12px; color: #ff3b30;${result.message}/div; return; } if (result.data.length 0) { resultEl.innerHTML div stylepadding: 12px; text-align: center;未找到匹配文件/div; return; } let html ; result.data.forEach(item { html div classresult-item div${item.name} span stylecolor: #007aff;(${item.type})/span/div div classresult-path${item.path}/div /div ; }); resultEl.innerHTML html; } // 執(zhí)行系統(tǒng)命令 function execCommand() { const cmd document.getElementById(command-input).value.trim(); window.toolboxAPI.execCommand(cmd); } /script /body /html四、調試與部署1. 本地調試在項目根目錄執(zhí)行命令啟動應用測試功能是否正常bash運行npm start可分別測試設備信息查詢、文件搜索、命令執(zhí)行功能調試 UI 樣式與交互邏輯。2. 鴻蒙設備部署1打包應用執(zhí)行打包命令生成鴻蒙兼容的 Linux-x64 版本bash運行npm run package打包完成后在dist目錄下會生成harmony-toolbox-linux-x64文件夾。2運行應用將打包后的文件夾拷貝到鴻蒙設備打開鴻蒙設備終端進入應用目錄賦予執(zhí)行權限bash運行cd /home/user/Documents/harmony-toolbox-linux-x64 chmod x harmony-toolbox啟動應用bash運行./harmony-toolbox3. 常見問題排查問題現(xiàn)象解決方案文件搜索無結果檢查搜索關鍵詞是否正確鴻蒙設備是否有對應文件忽略無權限目錄的報錯命令執(zhí)行失敗確保輸入的是 Linux 命令鴻蒙設備已開啟 Linux 兼容層部分命令需要 root 權限應用啟動白屏檢查main.js中contextIsolation是否設為false五、總結與擴展本文開發(fā)的鴻蒙系統(tǒng)工具箱是一個輕量化、高實用性的 Electron 應用核心亮點在于功能貼合鴻蒙設備使用場景解決實際需求代碼模塊化程度高便于拓展新功能完全基于前端技術棧零成本適配鴻蒙系統(tǒng)。拓展方向添加進程管理功能查看 / 結束鴻蒙設備進程集成網絡測速測試鴻蒙設備的網絡上傳 / 下載速度支持文件快捷操作雙擊搜索結果打開文件 / 文件夾打包為 HAP 安裝包發(fā)布到鴻蒙應用市場。文末標簽#鴻蒙OS #Electron #跨端開發(fā) #前端開發(fā) #系統(tǒng)工具 #代碼實戰(zhàn)歡迎大家加入[開源鴻蒙跨平臺開發(fā)者社區(qū)](https://openharmonycrossplatform.csdn.net)一起共建開源鴻蒙跨平臺生態(tài)。