第7章:Electron文件系统操作(1)

7.1 使用 Node.js 文件系统模块

Electron 可以直接使用 Node.js 提供的文件系统模块 fs 进行文件操作。以下是一些基本操作的示例。

7.1.1 读取文件

主进程代码

const { app, BrowserWindow, ipcMain } = require('electron');
const fs = require('fs');
const path = require('path');

let mainWindow;

const createMainWindow = () => {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      nodeIntegration: false
    }
  });

  mainWindow.loadFile('index.html');
  mainWindow.webContents.openDevTools();
  mainWindow.on('closed', () => {
    mainWindow = null;
  });
};

app.on('ready', createMainWindow);
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});
app.on('activate', () => {
  if (mainWindow === null) {
    createMainWindow();
  }
});

// 处理文件读取请求
ipcMain.handle('read-file', async (event, filePath) => {
  try {
    const data = fs.readFileSync(filePath, 'utf8');
    return { success: true, data };
  } catch (err) {
    return { success: false, error: err.message };
  }
});

预加载脚本(preload.js)

const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electronAPI', {
  readFile: (filePath) => ipcRenderer.invoke('read-file', filePath)
});

渲染进程代码

<!DOCTYPE html>
<html>
<head>
  <title>File System Operations</title>
</head>
<body>
  <h1>Read File Example</h1>
  <input type="file" id="fileInput">
  <pre id="fileContent"></pre>

  <script>
    document.getElementById('fileInput').addEventListener('change', async (event) => {
      const file = event.target.files[0];
      if (file) {
        const result = await window.electronAPI.readFile(file.path);
        if (result.success) {
          document.getElementById('fileContent').innerText = result.data;
        } else {
          document.getElementById('fileContent').innerText = 'Error: ' + result.error;
        }
      }
    });
  </script>
</body>
</html>

在这里插入图片描述

7.1.2 写入文件

主进程代码

const { app, BrowserWindow, ipcMain } = require('electron');
const fs = require('fs');
const path = require('path');

let mainWindow;

const createMainWindow = () => {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      nodeIntegration: false
    }
  });

  mainWindow.loadFile('index.html');
  mainWindow.webContents.openDevTools();
  mainWindow.on('closed', () => {
    mainWindow = null;
  });
};

app.on('ready', createMainWindow);
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});
app.on('activate', () => {
  if (mainWindow === null) {
    createMainWindow();
  }
});

// 处理文件写入请求
ipcMain.handle('write-file', async (event, filePath, content) => {
  try {
    fs.writeFileSync(filePath, content, 'utf8');
    return { success: true };
  } catch (err) {
    return { success: false, error: err.message };
  }
});

预加载脚本(preload.js)

const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electronAPI', {
  writeFile: (filePath, content) => ipcRenderer.invoke('write-file', filePath, content)
});

渲染进程代码

<!DOCTYPE html>
<html>
<head>
  <title>File System Operations</title>
</head>
<body>
  <h1>Write File Example</h1>
  <input type="text" id="fileName" placeholder="Enter file name">
  <textarea id="fileContent" placeholder="Enter file content"></textarea>
  <button id="saveFile">Save File</button>
  <p id="statusMessage"></p>

  <script>
    document.getElementById('saveFile').addEventListener('click', async () => {
      const fileName = document.getElementById('fileName').value;
      const fileContent = document.getElementById('fileContent').value;

      if (fileName && fileContent) {
        const result = await window.electronAPI.writeFile(fileName, fileContent);
        if (result.success) {
          document.getElementById('statusMessage').innerText = 'File saved successfully!';
        } else {
          document.getElementById('statusMessage').innerText = 'Error: ' + result.error;
        }
      }
    });
  </script>
</body>
</html>
  • 36
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值