# electron-utilityprocess-messagechannel **Repository Path**: fe521/electron-utilityprocess-messagechannel ## Basic Information - **Project Name**: electron-utilityprocess-messagechannel - **Description**: 调研 electron 进程间通信 使用 utilityProcess、MessageChannelMain 方式进行 - **Primary Language**: Unknown - **License**: CC0-1.0 - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2023-10-26 - **Last Updated**: 2023-12-30 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # electron-process 局域网文件传输,有点绕,要走动态链接库的方式,并且只能在子进程 -子进程再创建 worker 线程中进行。 渲染进程发起任务(db 存储) -> 主进程 -> 子进程 -> worker 线程(同步任务) -> 进度返回 ->子进程(db 更新) - 主进程 - 渲染进程 - 显示 UI 进度 调研 electron 进程间通信 使用 utilityProcess、MessageChannelMain 方式进行 ## Electron 中的消息端口 https://www.electronjs.org/zh/docs/latest/tutorial/message-ports ## electron utility-process https://www.electronjs.org/zh/docs/latest/api/utility-process ## electron 渲染进程 - 到主进程 - 子进程 - worker 线程之间的通信 1. 渲染进程发送消息到主线程 2. 主线程 fork 子进程,并把 `MessageChannelMain port1`、`MessageChannelMain port2` 分别发送给子进程和渲染进程 ```js // Main process ipcMain.handle("start-upload", (event, uuid) => { const { port1, port2 } = new MessageChannelMain(); const child = utilityProcess.fork(path.join(__dirname, "subprocess.js")); child.postMessage({ message: "hello", uuid }, [port1]); mainWindow.webContents.postMessage(uuid, null, [port2]); }); ``` 3. 渲染进程监听 `MessageChannelMain port2` 消息事件 4. 子进程创建 worker 线程,同时创建 node 的 MessageChannel 5. 把 `MessageChannel port2` 发给 worker 线程,`MessageChannel port1` 接收 worker 发回来的消息 6. `MessageChannel port1`接收到消息转发给 `MessageChannelMain port1` 7. `MessageChannelMain port1` 发送给 `MessageChannelMain port2` ```js // Child process const { Worker, MessageChannel } = require("worker_threads"); process.parentPort.once("message", (event) => { console.log("event", event.data); const [port] = event.ports; const worker = new Worker("./worker.js"); // 引用 worker.js 文件 const channel = new MessageChannel(); // 从工作线程接收消息 channel.port1.on("message", (message) => { // console.log("Received from worker:", message); port.postMessage(message); if (message.progress === 100) { port.close(); channel.port1.close(); } }); // 向工作线程发送消息 worker.postMessage({ port: channel.port2, uuid: event.data.uuid }, [ channel.port2, ]); }); ``` ## node.js 主线程与 worker 线程之间通信 examples/node-message-channel main.js 主线程代码 worker.js 工作线程的代码 ## ffi-napi 在 electron 高版本 无法运行的问题 1. 使用 electron@20.3.8及以前的版本可以 https://github.com/node-ffi-napi/node-ffi-napi/issues/238#issuecomment-1416872829 2. 使用别人 fork 修复的版本的 ffi-napi ref-napi https://github.com/node-ffi-napi/node-ffi-napi/issues/238#issuecomment-1578256269 ```bash npm i @breush/ref-napi npm i @breush/ffi-napi ``` ## electron rebulid https://www.npmjs.com/package/@electron/rebuild ``` npm i @electron/rebuild ``` ## 中文路径问题 ``` npm i iconv-lite -S ```