electron小例子

说明:该例子主要实现把输入框中的文字保存到本地的文本文档中。

在main中添加几句代码

const ipcMain = electron.ipcMain;
const dialog = electron.dialog;
ipcMain.on("openDir", function (e) {
    var fileName = dialog.showOpenDialog(mainWindow, {title: "选择一个目录", properties: ["openDirectory"]});
    e.returnValue = fileName ? fileName : null;
});

这段代码防止文件没有名字而出错

 

html代码

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Hello World!</title>
 6 </head>
 7 <body>
 8 <button id="btn-select-dest-dir">选择保存的目录</button>
 9 <form id="form-data">
10     <div>
11         <textarea name="txt" style="width: 300px;height: 200px" required="required"></textarea>
12     </div>
13     <div>
14         <input type="submit" value="保存">
15     </div>
16 </form>
17 </body>
18 
19 <script>
20     // You can also require other files to run in this process
21     require('./renderer.js')
22 </script>
23 </html>

renderer代码

 1 // This file is required by the index.html file and will
 2 // be executed in the renderer process for that window.
 3 // All of the Node.js APIs are available in this process.
 4 const {ipcRenderer}=require("electron");
 5 const fs = require("fs");
 6 
 7 class Renderer {
 8     constructor() {
 9         this.btnSelectDestDir = document.getElementById("btn-select-dest-dir");
10         this.formSaveData = document.getElementById("form-data");
11 
12         this.addListeners();
13     }
14 
15     addListeners() {
16         var self = this;
17 
18         this.btnSelectDestDir.onclick = function () {
19             var files = ipcRenderer.sendSync("openDir");
20 
21             if (files && files.length) {
22                 self.destDir = files[0];
23             }
24         };
25 
26         this.formSaveData.onsubmit = function (e) {
27             e.preventDefault();
28 
29             if (!self.destDir) {
30                 alert("请选择要保存的目录");
31                 return;
32             }
33 
34             var destFile = `${self.destDir}/data.txt`;
35             fs.writeFile(destFile, this["txt"].value, function (err) {
36                 if (!err) {
37                     alert(`成功保存文件${destFile}`);
38                 } else {
39                     alert("无法保存文件");
40                 }
41             })
42         };
43     }
44 }
45 new Renderer();

运行即可

 补充:在main.js里面的

可以修改运行文件的路径。。。

posted @ 2016-11-14 18:05  晨落梦公子  阅读(2844)  评论(0编辑  收藏  举报