项目创建,请参考:
【Electron】创建项目Hello Word
主进程与渲染进程通信,请参考:
【Electron】main process(主进程)和web page(渲染进程) 通信
一、项目结构
二、实现代码
index.html
<!doctype html> <html> <head> <meta charset="utf-8" /> <title>测试</title> <script src="index.js"></script> </head> <body > <p>Hello World</p> <button onclick="unzip();">解压</button> </body> </html>
index.js
扫描二维码关注公众号,回复:
1759061 查看本文章
const {ipcRenderer} = require('electron') /** * 解压 */ function unzip(){ var a="f:\\1\\1.zip";//需要解压文件的路径 var b="f:\\3\\";//解压文件存放路径 ipcRenderer.send('unzip',a+"+"+b) }
main.js
const electron = require('electron');// 控制应用生命周期的模块 const {app} = electron;// 创建本地浏览器窗口的模块 const {BrowserWindow} = electron; // 指向窗口对象的一个全局引用,如果没有这个引用,那么当该javascript对象被垃圾回收的// 时候该窗口将会自动关闭 let win; function createWindow() { // 创建一个新的浏览器窗口 win = new BrowserWindow({width: 1104, height: 620});//570+50 // 并且装载应用的index.html页面 win.loadURL(`file://${__dirname}/html/index.html`); // 打开开发工具页面 win.webContents.openDevTools(); // 当窗口关闭时调用的方法 win.on('closed', () => { // 解除窗口对象的引用,通常而言如果应用支持多个窗口的话,你会在一个数组里 // 存放窗口对象,在窗口关闭的时候应当删除相应的元素。 win = null; }); } // 当Electron完成初始化并且已经创建了浏览器窗口,则该方法将会被调用。// 有些API只能在该事件发生后才能被使用。 app.on('ready', createWindow); // 当所有的窗口被关闭后退出应用 app.on('window-all-closed', () => { // 对于OS X系统,应用和相应的菜单栏会一直激活直到用户通过Cmd + Q显式退出 if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', () => { // 对于OS X系统,当dock图标被点击后会重新创建一个app窗口,并且不会有其他 // 窗口打开 if (win === null) { createWindow(); } }); // 在这个文件后面你可以直接包含你应用特定的由主进程运行的代码。// 也可以把这些代码放在另一个文件中然后在这里导入。 /*******************实现代码************************** */ //通信模块,mian process与renderer process(web page) const {ipcMain} = require('electron')//监听web page里发出的message const fs = require('fs')//监听web page里发出的message const unzip=require('./unzip/unzip') let installpath;//文件路径 let route; //解压后路径 ipcMain.on('unzip', (event, args) => { var arr=args.split("+"); installpath=arr[0]; route=arr[1]; fs.createReadStream(installpath).pipe(unzip.Extract({path:route})); }) /*******************实现代码************************** */
gulpfile.js
// 获取依赖 var gulp = require('gulp'), childProcess = require('child_process'), electron = require('electron-prebuilt'); // 创建 gulp 任务 gulp.task('run', function () { childProcess.spawn(electron, ['--debug=5858','.'], {stdio:'inherit'}); });
package.json
{ "name": "package.json", "version": "1.4.0", "description": "hello world", "main": "app/main.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "NS", "license": "ISC", "devDependencies": { "electron-prebuilt": "^1.4.13", "gulp": "^3.9.1" } }
出现的问题:
1.Cannot find module 'setimmediate'
解决方案:
使用cnpm install -d 可以自动配置package.json,并安装所有需要依赖的包,请确定package.json里有添加相应的依赖配置。