如何通过Electron获取Windows/Mac系统中运行应用的信息及CPU使用率?
Absolutely—Electron lets you tap into Node.js's ecosystem from its main process, which gives you access to tools that can fetch running app details and CPU usage across Windows and macOS. Here's a straightforward breakdown of how to implement this:
Core Approach
Electron's main process (unlike the sandboxed renderer process) can directly use Node.js modules that interact with the underlying OS. We'll leverage popular cross-platform libraries to get process data, then share that data with your app's UI via IPC (Inter-Process Communication).
Recommended Libraries
Two reliable libraries for this task are:
systeminformation: A comprehensive library covering almost all system metrics, including process lists and per-process CPU usage.pidusage: A lighter-weight option focused specifically on process CPU/memory usage.
We'll use systeminformation for this example—it's more feature-complete for your needs.
Step-by-Step Implementation
1. Install the Dependencies
First, add the library to your project:
npm install systeminformation
2. Fetch Process Data in the Main Process
Create or update your main process file (usually main.js) to retrieve process info and send it to the renderer:
const { app, BrowserWindow, ipcMain } = require('electron'); const si = require('systeminformation'); let mainWindow; function createWindow() { mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: false, // Keep sandbox enabled for security contextIsolation: true, preload: `${__dirname}/preload.js` // Use preload script for safe IPC } }); mainWindow.loadFile('index.html'); } // Listen for requests from the renderer to get process data ipcMain.handle('get-process-data', async () => { try { // Fetch all running processes const processes = await si.processes(); // Filter to focus on user-facing apps (adjust this filter as needed) const appProcesses = processes.list.filter(process => { return process.name && !process.path.includes('System32') && !process.path.includes('Library/System'); }); // Map to return only relevant details return appProcesses.map(process => ({ name: process.name, pid: process.pid, cpuUsage: `${process.cpu.toFixed(2)}%`, path: process.path })); } catch (error) { console.error('Error fetching process data:', error); throw error; } }); app.whenReady().then(createWindow);
3. Set Up a Preload Script for IPC
Create a preload.js file to safely expose IPC methods to the renderer:
const { contextBridge, ipcRenderer } = require('electron'); contextBridge.exposeInMainWorld('electronAPI', { getProcessData: () => ipcRenderer.invoke('get-process-data') });
4. Display Data in the Renderer (UI)
Update your index.html to fetch and display the process data:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Process Monitor</title> <style> table { width: 100%; border-collapse: collapse; margin-top: 1rem; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } button { padding: 0.5rem 1rem; cursor: pointer; } </style> </head> <body> <h1>Running Apps & CPU Usage</h1> <button onclick="fetchProcessData()">Refresh Data</button> <table id="processTable"> <thead> <tr> <th>App Name</th> <th>PID</th> <th>CPU Usage</th> <th>Path</th> </tr> </thead> <tbody></tbody> </table> <script> async function fetchProcessData() { const tableBody = document.querySelector('#processTable tbody'); tableBody.innerHTML = ''; try { const processes = await window.electronAPI.getProcessData(); processes.forEach(process => { const row = document.createElement('tr'); row.innerHTML = ` <td>${process.name}</td> <td>${process.pid}</td> <td>${process.cpuUsage}</td> <td>${process.path}</td> `; tableBody.appendChild(row); }); } catch (error) { alert('Failed to fetch process data: ' + error.message); } } // Fetch data when the page loads window.onload = fetchProcessData; </script> </body> </html>
Key Notes
- Permissions: On macOS, you might need to grant your app accessibility permissions (System Settings > Privacy & Security > Accessibility) to fetch full process details. On Windows, no special permissions are usually required unless accessing restricted system processes.
- Performance: If you need real-time updates, add a
setIntervalto refresh data, but be mindful of system resource usage—avoid overly frequent calls. - Security: Always keep
contextIsolationenabled and use a preload script for IPC. This prevents exposing Node.js APIs directly to the renderer, avoiding potential security risks.
This setup will let you reliably get running app information and their CPU usage across both Windows and macOS using Electron.
内容的提问来源于stack exchange,提问作者Anand Vaidya

