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>