You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Electron中使用Angular将应用数据保存至指定路径

Electron 应用将数据持久化到 AppData 的可行方案

一、解决 session 未定义的错误

你碰到的 Cannot destructure property 'session' of 'electron' as it is undefined 问题,核心是 Electron 模块导入方式错误:

  • 主进程中需直接从 electron 包解构:
    const { session } = require('electron');
    
  • 渲染进程不能直接访问 electron 对象,需通过 ipcRenderer 调用主进程的 session 相关逻辑,或在 Electron 14+ 中手动启用 remote 模块后再导入。

二、直接读写 AppData 目录的基础方案

1. 获取 AppData 路径

Electron 内置方法可直接获取系统标准路径,无需硬编码:

const { app } = require('electron');
const path = require('path');
// 获取系统 AppData 目录,再创建应用专属存储文件夹
const appStorageDir = path.join(app.getPath('appData'), '你的应用名称');

2. 用 fs 模块实现文件读写

结合 Node.js 的 fs 模块完成数据持久化,注意先确保目录存在:

const fs = require('fs').promises;

// 确保存储目录存在
async function ensureStorageDir() {
  try {
    await fs.access(appStorageDir);
  } catch {
    await fs.mkdir(appStorageDir, { recursive: true });
  }
}

// 保存数据到 JSON 文件
async function saveData(data) {
  await ensureStorageDir();
  const filePath = path.join(appStorageDir, 'appData.json');
  await fs.writeFile(filePath, JSON.stringify(data, null, 2));
}

// 读取存储的数据
async function loadData() {
  const filePath = path.join(appStorageDir, 'appData.json');
  try {
    const rawData = await fs.readFile(filePath, 'utf8');
    return JSON.parse(rawData);
  } catch {
    // 文件不存在时返回默认值
    return {};
  }
}

三、省心的第三方库方案

如果不想手动处理文件细节,推荐用专门的持久化库:

  • electron-store:专为 Electron 设计的键值对存储,默认将数据存在 AppData,用法极简:
    const Store = require('electron-store');
    const store = new Store();
    
    // 保存数据
    store.set('userConfig', { theme: 'dark', autoSync: true });
    // 读取数据
    const userConfig = store.get('userConfig');
    
  • lowdb:轻量级 JSON 数据库,可指定存储路径到 AppData,适合复杂数据结构场景。

四、Cookie 存储的正确姿势

如果坚持用 Cookie 方式,必须在主进程中操作,且设置持久化有效期:

const { session } = require('electron');

// 在主进程中设置持久化 Cookie
session.defaultSession.cookies.set({
  url: 'app://localhost', // 自定义本地域名
  name: 'persistData',
  value: JSON.stringify({ userId: 1001 }),
  expirationDate: Date.now() / 1000 + 365 * 24 * 60 * 60, // 1年有效期
  path: '/',
  httpOnly: true,
  secure: false
}).then(() => console.log('Cookie 保存成功'))
  .catch(err => console.error('Cookie 保存失败:', err));

内容的提问来源于stack exchange,提问作者latte164

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 03:54:12