electron-game-quickstart/electron/main.ts

40 lines
1.5 KiB
TypeScript

import { app, BrowserWindow, ipcMain } from 'electron';
import path from 'path';
import fs from 'fs/promises';
function createWindow() {
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
autoplayPolicy: 'no-user-gesture-required',
backgroundThrottling: false,
nodeIntegration: false,
},
});
mainWindow.loadFile(path.join(__dirname, '../dist/index.html'));
}
app.on('ready', createWindow);
ipcMain.handle('read-file', async (event: any, filePath: string) => {
const userDataPath = app.getPath('userData');
const fullPath = path.resolve(userDataPath, filePath);
if (!fullPath.startsWith(userDataPath)) throw new Error('Access denied');
return fs.readFile(fullPath, { encoding: 'utf-8' });
});
ipcMain.handle('write-file', async (event: any, filePath: string, content: any) => {
const userDataPath = app.getPath('userData');
const fullPath = path.resolve(userDataPath, filePath);
if (!fullPath.startsWith(userDataPath)) throw new Error('Access denied');
await fs.writeFile(fullPath, content, { encoding: 'utf-8' });
});
ipcMain.handle('list-files', async (event: any, dirPath: string) => {
const userDataPath = app.getPath('userData');
const fullPath = path.resolve(userDataPath, dirPath);
if (!fullPath.startsWith(userDataPath)) throw new Error('Access denied');
return fs.readdir(fullPath);
});