使用Electron读取本地文件

Electron原来叫Atom Shell ,可以用Web技术搭建桌面端程序,以Electron为基础,可以用HTML,CSS和javascriptpt实现程序逻辑和用户桌面,Electron程序一般有主进程和渲染进程,主进程是启动程序的Node脚本,提供对原生的node模块访问。渲染进程是由chromium管理的Web界面。以下的内容介绍从零开始搭建一个读取本地文件的Electron项目。

一  运行简单项目

1.获取electron-quick-start基础项目

electron-quick-start项目是gitHub上提供的简单electron项目模板,包含运行基本Electron程序所必需的依赖项,获取这个项目,安装依赖项命令如下:

git clone https://github.com/atom/electron-quick-start
cd electron-quick-start
npm install

2. 运行与调试

运行命令代码如下:

npm run start

在win10上运行electron-quick-start项目效果如下所示:

注意:调试命令如下  ctrl+shift+i 

在此项目中,主进程是main.js,渲染进程是index.html,preload.js是主进程中的预装载代码,renderer.js是渲染进程中渲染代码。

二  读取本地文件

1.渲染进程index.html代码

首行在渲染进程index.html中增加一个<pre>标签用于展示读取的本地文件内容,代码如下所示:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'">
    <link href="./styles.css" rel="stylesheet">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using Node.js <span id="node-version"></span>,
    Chromium <span id="chrome-version"></span>,
    and Electron <span id="electron-version"></span>.

    <pre id="source"></pre>
    
    <!-- You can also require other files to run in this process -->
    <script src="./renderer.js"></script>
  </body> 
</html>

2. 主进程main.js

在主进程的BrowserWindow中,我们传递一个配置参数webPreferences,它的可配置项:

        nodeIntegration: 是否集成node.js默认为false

        contextIsoIation:  上下文隔离,默认为true

        preload : 指定预加载的js文件绝对路径

只要把noteIntegration和contextIsolation配置为true和false即可,但这是一种不安全的行为,在Electron中,它推荐在preload中操作node, 主进程main.js代码如下 

// Modules to control application life and create native browser window
const { app, BrowserWindow } = require('electron')
const path = require('node:path')

function createWindow () {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
 // mainWindow.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

此时我们就可以在preload.js操作node.js ,代码如下:

//preload.js
console.log(process.platform)

此时运行,使用调试模式可以查看自己电脑操作系统,此时仅能在preload中操作node.js。

3.主进程子代码preload.js

Electron提供一个api为contextBridge,contextBridge在Electron中用于在主进程和渲染进程之间建立安全的通信通道,它提供的主要API有:

exposeInMainWorld(apiKey,api):

        apiKey: string 将API挂载到window的键。 API可通过windows[apikey]访问。

        api:   any  需要映射的node.js模块。

exposeInIsolatedWorld(worldId, apiKey, api):

   worldId Integer 要注入的API的ID,0是默认使用ID,999是Electron中的contextIsolation使用的ID,使用999将在preload上下文暴露对象,建议使用1000+创建隔离的world。

        apiKey: string 将API挂载到window的键。 API可通过windows[apikey]访问。

        api:   any  需要映射的node.js模块

在此项目中,使用exposeInMainWorld在主进程与渲染进程之间,建立安全通道,代码如下:

/**
 * The preload script runs before `index.html` is loaded
 * in the renderer. It has access to web APIs as well as
 * Electron's renderer process modules and some polyfilled
 * Node.js functions.
 *
 * https://www.electronjs.org/docs/latest/tutorial/sandbox
 */

const { contextBridge }=require("electron")
const fs=require('fs')
contextBridge.exposeInMainWorld('electronfs',fs)


window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  }

  for (const type of ['chrome', 'node', 'electron']) {
    replaceText(`${type}-version`, process.versions[type])
  }
})

4.渲染进程子代码renderer.js

renderer.js是渲染进程的子代码,通过<script src='./renderer.js'></script>引入到渲染进程, 代码如下:

/**
 * This file is loaded via the <script> tag in the index.html file and will
 * be executed in the renderer process for that window. No Node.js APIs are
 * available in this process because `nodeIntegration` is turned off and
 * `contextIsolation` is turned on. Use the contextBridge API in `preload.js`
 * to expose Node.js functionality from the main process.
 */


electronfs.readFile('./main.js','utf8',(err,data)=>{
    if(err) {
        console.err('读取文件失败',err)
    }  else {
        document.getElementById("source").innerHTML=data
    }
})

使用npm run start 运行后,效果如下:

此文主要介绍如何使用Electron操作fs模块,读取本地文件main.js内容,并在浏览窗口中显示 。主要有获取electron-quick-start项目并运行,建立主进程和渲染进程之间安全通道,在渲染进程中使用node.js 的fs模块读取本地文件main.js并在浏览窗口中显示。

### 实现 Vue2 和 Electron 读取本地配置文件 为了在基于 Vue2 的 Electron 应用程序中实现读取本地配置文件的功能,可以利用 Node.js 提供的 `fs` 模块来访问文件系统。下面展示了一个简单的方式来进行此操作。 #### 使用 fs 模块读取 JSON 配置文件 由于 Electron 可以直接调用 Node.js API,在主进程中可以通过引入 `fs` 来加载并解析位于应用资源目录下的 JSON 文件作为配置项[^1]: ```javascript // main.js (Electron 主进程) const { app, BrowserWindow } = require('electron'); const path = require('path'); const fs = require('fs'); function loadConfig() { try { const configPath = path.join(app.getPath('userData'), 'config.json'); // 获取用户数据路径下名为 config.json 的文件位置 let rawData = fs.readFileSync(configPath); // 同步方式读取文件内容 return JSON.parse(rawData.toString()); // 将其转换成 JavaScript 对象返回 } catch (err) { console.error(err); throw new Error("Failed to read configuration file"); } } ``` 为了让前端部分能够获取到这些设置信息,可以在创建窗口之前先执行上述函数并将结果传递给渲染线程或者通过 IPC 渠道发送过去。 #### 前端接收配置信息 如果选择后者,则需要定义好通信接口以便于前后端交互;而在前者的情况下可以直接把对象挂载至全局变量上方便组件随时存取: ```html <!-- index.html --> <script> window.configs = null; // 定义一个用于存储配置的地方 if (!process.env.IS_WEB) { // 判断当前环境是不是 Web 平台(即是否处于打包后的桌面环境中) window.addEventListener('DOMContentLoaded', () => { const preloadScript = document.createElement('script'); preloadScript.src = './preload.js'; document.head.appendChild(preloadScript); preloadScript.onload = function () { configs = ipcRenderer.sendSync('get-config'); // 发送同步消息请求配置数据 }; }); } else { // 如果是在浏览器里打开则模拟一些默认参数 window.configs = {}; } </script> ``` 这里假设已经有一个预加载脚本 (`preload.js`) 设置好了必要的权限让网页能发起跨域请求以及使用 nodeIntegration 功能。 #### 创建 Preload 脚本处理逻辑 最后一步就是编写这个中间件用来桥接两个世界之间的沟壑——也就是所谓的 “Preload Script”。它负责监听来自页面的消息并向后台转发查询指令,同时也可反过来向 HTML 页面暴露特定的能力或属性: ```javascript // preload.js const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld( "api", { getConfig: () => ipcRenderer.invoke('get-config') // 注册方法名及其对应的处理器 } ) module.exports = {} ``` 此时再回到最初提到过的主流程代码那里补充一句用来响应此类事件的实际动作即可完成整个闭环设计: ```javascript // 继续上面的例子... app.whenReady().then(() => { ... mainWindow.webContents.on('did-finish-load', async () => { await mainWindow.webContents.executeJavaScript(`configs=${JSON.stringify(loadConfig())};`); }); ipcMain.handle('get-config', async (_event) => { return loadConfig(); }) }); ``` 这样就实现了从启动时自动注入配置直到按需动态拉取最新版本的一套完整的解决方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值