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 }));
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、Node.js v24.22.3 本地运行环境。
入口文件:projects/electron-practical-lab/explore-practical.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-practical.mjs,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1092.zip
课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a1081.zip