Appearance
electron-store
一个用于 Electron 应用程序的简单数据持久化存储方案
安装
bash
pnpm add electron-store基础配置
在主进程或渲染进程中配置:
ts
import Store from 'electron-store'
// 创建存储实例
const store = new Store({
// 可选,加密配置
encryptionKey: 'my-secret-key',
// 可选,数据结构类型定义
defaults: {
config: {
theme: 'light',
language: 'zh-CN',
},
userInfo: {
name: '',
email: '',
},
},
})使用示例
基本操作
ts
// 设置值
store.set('user.name', 'John')
store.set('user.email', 'john@example.com')
// 获取值
const userName = store.get('user.name')
const userEmail = store.get('user.email')
// 删除值
store.delete('user.email')
// 清空存储
store.clear()
// 检查键是否存在
const hasName = store.has('user.name')在渲染进程中使用
ts
import { ipcRenderer } from 'electron'
// 通过 IPC 与主进程通信
ipcRenderer.invoke('electron-store-get', 'user.name')
ipcRenderer.invoke('electron-store-set', 'user.name', 'John')高级配置
ts
import Store from 'electron-store'
import { app } from 'electron'
const store = new Store({
// 存储文件名
name: 'config',
// 存储文件路径
cwd: app.getPath('userData'),
// 文件扩展名
fileExtension: 'conf',
// 序列化配置
serialize: (value) => JSON.stringify(value, null, 2),
deserialize: (value) => JSON.parse(value),
// 数据迁移
migrations: {
'1.0.0': (store) => {
const oldConfig = store.get('config')
if (oldConfig) {
store.set('settings', oldConfig)
store.delete('config')
}
},
},
// 数据校验
schema: {
settings: {
type: 'object',
properties: {
theme: {
type: 'string',
enum: ['light', 'dark'],
},
language: {
type: 'string',
pattern: '^[a-z]{2}-[A-Z]{2}$',
},
},
},
},
// 监听变更
watch: true,
// 事件处理
events: {
change: (key, value) => {
console.log(`配置项 ${key} 已更改为:`, value)
},
},
})