步骤分析

  • 点击菜单按钮打开文件
  • 读取文件路径
  • 使用fs模块读取文件内容
  • 将文件内容渲染到页面上

点击菜单按钮打开文件

 创建模板菜单,将其添加在主进程中

let template =[
    {
        label:'文件',
        submenu:[
            {
                label:'新建',
                click:function(){

                }
            },
            {
                label:'打开',
                click:function(){
                    //主进程通知渲染进程操作文件
                    BrowserWindow.getFocusedWindow().webContents.send('action')
                }
            },
            {
                label:'保存',
                click:function(){
                	
                }
            },
            {
                type:'separator'
            },
            {
                label:'打印',
                click:function(){
                   
                }
            },
            {
                label:'退出',
                click:function(){
                    
                }
            }
        ]
    }
]

let m = Menu.buildFromTemplate(template)

Menu.setApplicationMenu(m)

读取文件渲染文件内容

 渲染进程接收到主进程发送的信息,并进行读取文件将文件内容渲染到页面上。

//引入ipcRenderer模块,remote模块
var {ipcRenderer,remote} = require('electron')
//引入fs模块
var fs = require('fs')
//获取文本框的dom 
var textAreaDom = document.querySelector('#textArea')

ipcRenderer.on('action',function(event,action){

            // 通过dialog打开文件
            remote.dialog.showOpenDialog({
            
                properties:['openFile']
             
            }).then(dir => {
				//通过fs模块读取文件内容
                var fsData = fs.readFileSync(dir.filePaths[0])
				//将fs模块中读取的内容渲染到文本输入框
                textAreaDom.value= fsData 
            }) 
      
    }
})

HTML文件

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="./static/css/index.css">    
  </head>
  <body>

    <textarea id="textArea"></textarea>

    <script src="./renderer/ipcRenderer.js"></script>
  </body>
</html>

 
 分享完毕。

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐