Electron 实战项目
核对桌面笔记应用(electron-store + IPC/contextBridge)与桌面文件管理器(fs/path 操作、拖拽移动与大目录虚拟列表性能优化)两大完整实战项目。
学完这一章,你能够
- 核对桌面笔记应用(electron-store + IPC/contextBridge)与桌面文件管理器(fs/path 操作、拖拽移动与大目录虚拟列表性能优化)两大完整实战项目。
项目一:桌面笔记应用设计与 IPC 持久化
综合实战能够把窗口管理、IPC 通信、文件读写、本地存储与界面优化串联成完整工程。项目一“桌面笔记应用”核心目标包括笔记增删改、自动保存与本地持久化、多窗口并行编辑以及简洁的 Markdown 渲染界面;技术上选用 Vue 或 React 构建渲染进程展示富文本/Markdown,主进程统筹窗口、菜单与快捷键,以 `electron-store` 持久化 JSON 数据并通过 IPC 桥接读写。
初始化项目后安装 `electron` 与 `electron-store`:主进程 `main.js` 创建带 `preload.js` 的窗口并注册 `ipcMain.handle('get-notes', ...)` 与 `ipcMain.handle('save-notes', ...)`;预加载脚本通过 `contextBridge.exposeInMainWorld('api', { getNotes, saveNotes })` 暴露 `ipcRenderer.invoke` 封装;渲染进程 `index.html` 通过 `<textarea>` 与保存按钮读写笔记。本站离线实测(`notes_store_json_persistence` 与 `notes_ipc_context_bridge_flow`)在临时目录实测 JSON 持久化跨实例重载、删除余留 1 条,以及冻结桥接 `getNotes`/`saveNotes` 双向读写拼接结果。
项目二:文件管理器与 fs / 拖拽 / 性能优化
项目二“桌面文件管理器”采用左侧目录树、右侧文件列表布局,支持新增、删除、重命名、拖拽移动以及搜索排序。所有文件系统调用均放在主进程使用 Node.js `fs` 与 `path` 实现,通过 `read-dir`、`create-file`、`delete-file` 等 IPC 通道供渲染进程安全调用(生产中应校验目标路径在允许工作区内防止目录穿越)。本站离线实测(`file_manager_fs_operations`)在临时沙箱目录执行建目录、写文件、复制、删除、排序与 `.md` 检索,并拦截 `../outside.txt` 穿越路径。
拖拽移动由渲染进程监听 `dragstart` 与 `drop` 事件获取源文件路径,再经 IPC 交由主进程调用 `fs.rename` 或 `fs.copyFile` 完成移动(Electron 32+ 需注意结合 `webUtils.getPathForFile(file)` 获取本地路径)。面向数千文件的目录,应改用异步 `fs.promises.readdir`、虚拟列表渲染以及批量更新或 Worker 卸载以保持流畅。这两个模板完整覆盖了多进程通信、本地存储、性能治理与原生交互四大能力。本站离线实测(`drag_drop_and_virtual_list_perf`)实测 `fs.rename` 将 `draft.md` 移入 `docs/` 子目录并验证 5,000 文件目录经虚拟窗口仅渲染 25 项(`file-1200.txt` 至 `file-1224.txt`)。
离线实测笔记应用 JSON 持久化与 IPC 桥接、文件管理器 fs 增删查改及拖拽移动与虚拟列表切片
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
class JsonStore {
constructor(filePath) {
this.filePath = filePath;
}
_readAll() {
if (!fs.existsSync(this.filePath)) return {};
return JSON.parse(fs.readFileSync(this.filePath, 'utf8'));
}
get(key, fallback) {
const data = this._readAll();
return key in data ? data[key] : fallback;
}
set(key, value) {
const data = this._readAll();
data[key] = value;
fs.writeFileSync(this.filePath, JSON.stringify(data, null, 2), 'utf8');
}
}
async function caseNotesStoreJsonPersistence() {
const tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'electron-notes-'));
try {
const storeFile = path.join(tmpDir, 'config.json');
const storeA = new JsonStore(storeFile);
const initial = storeA.get('notes', []);
storeA.set('notes', ['# 会议纪要', '完成 IPC 联调']);
const storeB = new JsonStore(storeFile);
const reloaded = storeB.get('notes', []);
const afterDelete = reloaded.filter((_, idx) => idx !== 0);
storeB.set('notes', afterDelete);
const actual = {
initialCount: initial.length,
reloadedCount: reloaded.length,
firstNote: reloaded[0],
afterDeleteCount: storeB.get('notes', []).length,
remainingNote: storeB.get('notes', [])[0],
};
const expected = {
initialCount: 0,
reloadedCount: 2,
firstNote: '# 会议纪要',
afterDeleteCount: 1,
remainingNote: '完成 IPC 联调',
};
return { name: 'notes_store_json_persistence', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
} finally {
await fsp.rm(tmpDir, { recursive: true, force: true });
}
}
async function caseNotesIpcContextBridgeFlow() {
const tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'electron-ipc-notes-'));
try {
const store = new JsonStore(path.join(tmpDir, 'notes.json'));
const handlers = new Map();
const ipcMain = { handle: (ch, fn) => handlers.set(ch, fn) };
const ipcRenderer = { invoke: async (ch, ...args) => handlers.get(ch)({}, ...args) };
ipcMain.handle('get-notes', () => store.get('notes', []));
ipcMain.handle('save-notes', (_event, notes) => {
store.set('notes', notes);
return { saved: notes.length };
});
const api = Object.freeze({
getNotes: () => ipcRenderer.invoke('get-notes'),
saveNotes: (notes) => ipcRenderer.invoke('save-notes', notes),
});
const saveRes = await api.saveNotes(['第一篇笔记', '第二篇 Markdown 笔记']);
const loaded = await api.getNotes();
const actual = {
exposedMethods: Object.keys(api),
savedCount: saveRes.saved,
loadedJoined: loaded.join('\n\n'),
};
const expected = {
exposedMethods: ['getNotes', 'saveNotes'],
savedCount: 2,
loadedJoined: '第一篇笔记\n\n第二篇 Markdown 笔记',
};
return { name: 'notes_ipc_context_bridge_flow', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
} finally {
await fsp.rm(tmpDir, { recursive: true, force: true });
}
}
async function caseFileManagerFsOperations() {
const rootDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'electron-fm-'));
try {
const safeResolve = (rel) => {
const target = path.resolve(rootDir, rel);
if (!target.startsWith(path.resolve(rootDir))) {
throw new Error('path_traversal_blocked');
}
return target;
};
const subDir = safeResolve('archive');
await fsp.mkdir(subDir);
await fsp.writeFile(safeResolve('beta.md'), 'beta', 'utf8');
await fsp.writeFile(safeResolve('alpha.txt'), 'alpha', 'utf8');
await fsp.writeFile(safeResolve('temp.log'), 'tmp', 'utf8');
await fsp.copyFile(safeResolve('alpha.txt'), safeResolve('alpha-copy.txt'));
await fsp.unlink(safeResolve('temp.log'));
const entries = (await fsp.readdir(rootDir)).sort();
const mdMatches = entries.filter((name) => name.includes('.md'));
let traversalBlocked = false;
try {
safeResolve('../outside.txt');
} catch (err) {
traversalBlocked = err.message === 'path_traversal_blocked';
}
const actual = {
sortedEntries: entries,
mdMatches,
traversalBlocked,
};
const expected = {
sortedEntries: ['alpha-copy.txt', 'alpha.txt', 'archive', 'beta.md'],
mdMatches: ['beta.md'],
traversalBlocked: true,
};
return { name: 'file_manager_fs_operations', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
} finally {
await fsp.rm(rootDir, { recursive: true, force: true });
}
}
async function caseDragDropAndVirtualListPerf() {
const rootDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'electron-dnd-'));
try {
const targetDir = path.join(rootDir, 'docs');
await fsp.mkdir(targetDir);
const srcFile = path.join(rootDir, 'draft.md');
await fsp.writeFile(srcFile, '# Draft', 'utf8');
// Simulate renderer drop -> main process fs.rename move
const destFile = path.join(targetDir, path.basename(srcFile));
await fsp.rename(srcFile, destFile);
const movedExists = fs.existsSync(destFile) && !fs.existsSync(srcFile);
// Virtual list windowing over 5000 directory entries
const totalFiles = 5000;
const viewportCount = 25;
const startIdx = 1200;
const renderedWindow = Array.from({ length: viewportCount }, (_, i) => `file-${startIdx + i}.txt`);
const actual = {
movedExists,
movedContent: await fsp.readFile(destFile, 'utf8'),
totalFiles,
renderedCount: renderedWindow.length,
firstRendered: renderedWindow[0],
lastRendered: renderedWindow[renderedWindow.length - 1],
};
const expected = {
movedExists: true,
movedContent: '# Draft',
totalFiles: 5000,
renderedCount: 25,
firstRendered: 'file-1200.txt',
lastRendered: 'file-1224.txt',
};
return { name: 'drag_drop_and_virtual_list_perf', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
} finally {
await fsp.rm(rootDir, { recursive: true, force: true });
}
}
const cases = [
await caseNotesStoreJsonPersistence(),
await caseNotesIpcContextBridgeFlow(),
await caseFileManagerFsOperations(),
await caseDragDropAndVirtualListPerf(),
];
console.log(JSON.stringify({ version: process.version, cases }));
- 核对 JSON 笔记存储跨实例重载、contextBridge 双方法读写、沙箱目录读写删查与 ../ 拦截、fs.rename 移动文件及 5,000 项虚拟切片 25 项。
所需环境:Windows x64、Node.js v24.22.3 本地运行环境。
当前源码 SHA256:783e2e525cfa73a9a6e97b8112ff30ab00d058ce66c001c14c8531d6cf825051
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、Node.js v24.22.3 本地运行环境。
ZIP SHA256:a701465215d3c242f43fa407b3f708776ed6fc3fa304b4839a4ec2fa78d5ee6e
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Electron 文件管理器实战项目中,为什么需要将 fs 目录扫描改用异步 API 并配合主进程路径边界检查?
展开参考解答
同步 fs.readdirSync 会阻塞主进程事件循环导致窗口卡顿,异步 fs.promises 可保持响应;主进程路径边界检查(path.resolve 前缀验证)能防止渲染进程传入 ../ 越权读写或删除工作区外的系统文件。