Electron 提供了一个对话框模块,可用于显示本地系统对话框,可用于打开和保存文件,已经消息的提供。javascript
下面咱们简单以实例的方式演习一下,表示建立一个应用,弹出一个文件打开的窗口,将文件的内容显示出来。html
建立一个新的main.js文件,并敲入下面的代码。java
const {app, BrowserWindow} = require('electron') const url = require('url') const path = require('path') const {ipcMain} = require('electron') let win function createWindow() { win = new BrowserWindow({width: 800, height: 600}) win.loadURL(url.format({ pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true })) } ipcMain.on('openFile', (event, path) => { const {dialog} = require('electron') const fs = require('fs') dialog.showOpenDialog(function (fileNames) { if(fileNames === undefined){ console.log("No file selected"); }else{ readFile(fileNames[0]); } }); function readFile(filepath){ fs.readFile(filepath, 'utf-8', (err, data) => { if(err){ alert("An error ocurred reading the file :" + err.message) return } // handle the file content event.sender.send('fileData', data) }) } }) app.on('ready', createWindow)
上面咱们使用了前面提到的IPC模块,用于从界面发送一个openFile的命令,接收到以后咱们显示一个文件打开的窗口,而且将文件的内容发送到前台的界面。app
如今咱们建立一个index.html文件electron
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>File read using system dialogs</title> </head> <body> <script type="text/javascript"> const { ipcRenderer } = require('electron') ipcRenderer.send('openFile', () => { console.log("Event sent."); }) ipcRenderer.on('fileData', (event, data) => { document.write(data) }) </script> </body> </html>
上面的代码主要的功能是向main线程发送一个openFile请求,再经过fileData的事件向界面显示文件的内容。ui
最终咱们的效果以下图所示url
线程
下面显示的是文件的内容code
 2017-08-12 17.06.49.png)orm
上面咱们只提供了显示文件打开的示例,一样的electron还提供保存文件以及显示消息的窗口。
dialog.showOpenDialog([browserWindow, ]options[, callback])
dialog.showSaveDialog([browserWindow, ]options[, callback])
显示保存文件窗口
dialog.showMessageBox([browserWindow, ]options[, callback])
dialog.showMessageBox({type:'info',title:"显示消息",message:'消息',detail:'这是一个提示的消息片断'},function(message){ console.log(message); })

dialog.showErrorBox(title, content) 显示错误消息
dialog.showErrorBox('显示提示消息',)

dialog.showCertificateTrustDialog([browserWindow, ]options, callback)