import { fork } from 'node:child_process';
import { EventEmitter } from 'node:events';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
// Child worker mode for real multi-process OS IPC demonstration
if (process.argv.includes('--ipc-worker')) {
process.on('message', (msg) => {
if (msg?.type === 'invoke' && msg.channel === 'renderer:echo') {
process.send({
type: 'reply',
id: msg.id,
workerPid: process.pid,
echo: `handled:${msg.payload}`,
});
} else if (msg?.type === 'shutdown') {
process.exit(0);
}
});
process.send({ type: 'ready', workerPid: process.pid });
} else {
const makeCase = (name, expected, actual) => ({
name,
passed: JSON.stringify(actual) === JSON.stringify(expected),
expected,
actual,
});
const cases = [];
// Case 1: Real OS-level multi-process IPC via child_process.fork
{
const selfFile = fileURLToPath(import.meta.url);
const ipcResult = await new Promise((resolve, reject) => {
const child = fork(selfFile, ['--ipc-worker'], { stdio: ['ignore', 'ignore', 'ignore', 'ipc'] });
let readyPid = null;
child.on('error', reject);
child.on('message', (msg) => {
if (msg.type === 'ready') {
readyPid = msg.workerPid;
child.send({ type: 'invoke', id: 101, channel: 'renderer:echo', payload: 'hello-main' });
} else if (msg.type === 'reply') {
child.send({ type: 'shutdown' });
resolve({
distinctProcessIds: readyPid !== process.pid && msg.workerPid === readyPid,
replyId: msg.id,
echo: msg.echo,
});
}
});
});
const expected = {
distinctProcessIds: true,
replyId: 101,
echo: 'handled:hello-main',
};
cases.push(makeCase('real_multiprocess_fork_ipc', expected, ipcResult));
}
// Case 2: ipcMain.handle / ipcRenderer.invoke file manager & dialog contract
{
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'electron-ch03-'));
try {
const sampleFile = path.join(tmpDir, 'notes.txt');
await fs.writeFile(sampleFile, 'Electron architecture verified', 'utf8');
const handlers = new Map();
const ipcMain = { handle: (ch, fn) => handlers.set(ch, fn) };
const ipcRenderer = {
invoke: async (ch, ...args) => {
const fn = handlers.get(ch);
if (!fn) throw new Error(`No handler for ${ch}`);
return await fn({ sender: 'renderer-1' }, ...args);
},
};
ipcMain.handle('show-dialog', async (_ev, message) => ({
response: 0,
message,
buttons: ['确定', '取消'],
}));
ipcMain.handle('select-file', async () => ({
canceled: false,
filePaths: [sampleFile],
allowedExtensions: ['txt', 'md', 'js', 'html', 'css'],
}));
ipcMain.handle('read-file', async (_ev, filePath) => {
try {
const content = await fs.readFile(filePath, 'utf8');
return { success: true, content };
} catch (err) {
return { success: false, error: err.code || err.message };
}
});
const dlg = await ipcRenderer.invoke('show-dialog', '你好,Electron!');
const sel = await ipcRenderer.invoke('select-file');
const okRead = await ipcRenderer.invoke('read-file', sel.filePaths[0]);
const missRead = await ipcRenderer.invoke('read-file', path.join(tmpDir, 'missing.txt'));
const expected = {
dialogResponse: 0,
selectedBasename: 'notes.txt',
readSuccess: true,
readContent: 'Electron architecture verified',
missingFileSuccess: false,
missingFileError: 'ENOENT',
};
const actual = {
dialogResponse: dlg.response,
selectedBasename: path.basename(sel.filePaths[0]),
readSuccess: okRead.success,
readContent: okRead.content,
missingFileSuccess: missRead.success,
missingFileError: missRead.error,
};
cases.push(makeCase('ipc_invoke_handle_and_file_manager', expected, actual));
} finally {
await fs.rm(tmpDir, { recursive: true, force: true });
}
}
// Case 3: Security architecture guardrails (CSP, sandbox, URL whitelist)
{
const webPreferences = {
nodeIntegration: false,
contextIsolation: true,
sandbox: true,
preload: 'preload.js',
};
const csp = "default-src 'self'; script-src 'self'";
const allowedOrigins = new Set(['https://docs.example.com', 'https://app.example.com']);
const isUrlAllowed = (raw) => {
try {
return allowedOrigins.has(new URL(raw).origin);
} catch {
return false;
}
};
const expected = {
safeWebPreferences: true,
cspBlocksUnsafeEval: true,
allowedUrlAccepted: true,
untrustedUrlBlocked: false,
};
const actual = {
safeWebPreferences:
webPreferences.nodeIntegration === false &&
webPreferences.contextIsolation === true &&
webPreferences.sandbox === true &&
Boolean(webPreferences.preload),
cspBlocksUnsafeEval: !csp.includes('unsafe-eval') && csp.includes("script-src 'self'"),
allowedUrlAccepted: isUrlAllowed('https://docs.example.com/guide'),
untrustedUrlBlocked: isUrlAllowed('https://evil.invalid/phish'),
};
cases.push(makeCase('sandbox_security_and_url_whitelist', expected, actual));
}
// Case 4: Boot pipeline, multi-window isolation & main-process module registry
{
const bootSteps = [
'electron .',
'main.js',
'app.whenReady',
'BrowserWindow',
'preload.js',
'index.html',
'ipc_request',
'main_reply',
'app.quit',
];
const windows = new Map([
['win1', { page: 'index.html', alive: true }],
['win2', { page: 'settings.html', alive: true }],
['win3', { page: 'dashboard.html', alive: true }],
]);
// Close window 2; windows 1 and 3 remain independent and alive
windows.get('win2').alive = false;
const alivePages = [...windows.values()].filter((w) => w.alive).map((w) => w.page);
const mainModules = [
'app',
'Menu',
'MenuItem',
'Tray',
'Notification',
'dialog',
'shell',
'nativeImage',
'clipboard',
'powerMonitor',
'screen',
];
const ipcDirections = new EventEmitter();
let seenR2M = false;
let seenM2R = false;
ipcDirections.on('r2m', () => {
seenR2M = true;
ipcDirections.emit('m2r');
});
ipcDirections.on('m2r', () => {
seenM2R = true;
});
ipcDirections.emit('r2m');
const expected = {
bootStepCount: 9,
alivePagesAfterClosingWin2: ['index.html', 'dashboard.html'],
mainModuleCount: 11,
bidirectionalIpcVerified: true,
};
const actual = {
bootStepCount: bootSteps.length,
alivePagesAfterClosingWin2: alivePages,
mainModuleCount: mainModules.length,
bidirectionalIpcVerified: seenR2M && seenM2R,
};
cases.push(makeCase('startup_pipeline_and_multiwindow_isolation', expected, actual));
}
console.log(JSON.stringify({ version: process.version, cases }));
}
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、Node.js v24.22.3 本地运行环境。
入口文件:projects/electron-architecture-lab/explore-architecture.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-architecture.mjs,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a1081.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1080.zip