Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于 electron 数据缓存 #32

Open
rottenpen opened this issue Jun 12, 2021 · 0 comments
Open

关于 electron 数据缓存 #32

rottenpen opened this issue Jun 12, 2021 · 0 comments
Labels

Comments

@rottenpen
Copy link
Owner

背景

最近给 appworks/tooltik 写 pr 顺便学一下怎么写 electron,发现官方并没有提供数据缓存的方案,就是大家自由发挥。

方案

  1. renderer 进程里的数据,我们可以直接当做网页开发,把数据存在 localstorage 里就可以了
  2. main 进程中的数据发挥空间就比较多,去掉 sqlite 这种学习/踩坑成本比较高的方案 (mac版微信也在用它加密本地数据),我们可以使用一些纯 js 实现的数据库。

lowdb.js

下面要说的 lowdb.js 是 一个基于 JSON 的非关系型数据库。它提供了一些很简单的 CURD 功能,只需要传入你希望存放的文件路径。与其说它是数据库,我更觉得它是一个提供类数据库操作方法的 file system。而且它在大部分情况下,不提供兜底能力,例如在 electron 打包安装后,在新环境里没有db文件,需要自己手动创建db文件。

import { join } from 'path'
import { Low, JSONFile } from 'lowdb'

// Use JSON file for storage
const file = join(__dirname, 'db.json')
const adapter = new JSONFile(file)
const db = new Low(adapter)

// Read data from JSON file, this will set db.data content
await db.read()

// If file.json doesn't exist, db.data will be null
// Set default data
db.data ||= { posts: [] }

// Create and query items using plain JS
db.data.posts.push('hello world')
db.data.posts[0]

// You can also use this syntax if you prefer
const { posts } = db.data
posts.push('hello world')

// Write db.data content to db.json
await db.write()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant