当前位置: 首页 > 软件库 > 大数据 > 数据存储 >

electron-store

授权协议 MIT License
开发语言 C#
所属分类 大数据、 数据存储
软件类型 开源软件
地区 不详
投 递 者 楚望
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

electron-store

Simple data persistence for your Electron app or module - Save and load user preferences, app state, cache, etc

Electron doesn't have a built-in way to persist user preferences and other data. This module handles that for you, so you can focus on building your app. The data is saved in a JSON file named config.json in app.getPath('userData').

You can use this module directly in both the main and renderer process. For use in the renderer process only, you need to call Store.initRenderer() in the main process, or create a new Store instance (new Store()) in the main process.





Install

$ npm install electron-store

Requires Electron 11 or later.

Usage

const Store = require('electron-store');

const store = new Store();

store.set('unicorn', '��');
console.log(store.get('unicorn'));
//=> '��'

// Use dot-notation to access nested properties
store.set('foo.bar', true);
console.log(store.get('foo'));
//=> {bar: true}

store.delete('unicorn');
console.log(store.get('unicorn'));
//=> undefined

API

Changes are written to disk atomically, so if the process crashes during a write, it will not corrupt the existing config.

Store(options?)

Returns a new instance.

options

Type: object

defaults

Type: object

Default values for the store items.

Note: The values in defaults will overwrite the default key in the schema option.

schema

type: object

JSON Schema to validate your config data.

Under the hood, the JSON Schema validator ajv is used to validate your config. We use JSON Schema draft-07 and support all validation keywords and formats.

You should define your schema as an object where each key is the name of your data's property and each value is a JSON schema used to validate that property. See more here.

Example:

const Store = require('electron-store');

const schema = {
	foo: {
		type: 'number',
		maximum: 100,
		minimum: 1,
		default: 50
	},
	bar: {
		type: 'string',
		format: 'url'
	}
};

const store = new Store({schema});

console.log(store.get('foo'));
//=> 50

store.set('foo', '1');
// [Error: Config schema violation: `foo` should be number]

Note: The default value will be overwritten by the defaults option if set.

migrations

Type: object

You can use migrations to perform operations to the store whenever a version is upgraded.

The migrations object should consist of a key-value pair of 'version': handler. The version can also be a semver range.

Example:

const Store = require('electron-store');

const store = new Store({
	migrations: {
		'0.0.1': store => {
			store.set('debugPhase', true);
		},
		'1.0.0': store => {
			store.delete('debugPhase');
			store.set('phase', '1.0.0');
		},
		'1.0.2': store => {
			store.set('phase', '1.0.2');
		},
		'>=2.0.0': store => {
			store.set('phase', '>=2.0.0');
		}
	}
});

name

Type: string
Default: 'config'

Name of the storage file (without extension).

This is useful if you want multiple storage files for your app. Or if you're making a reusable Electron module that persists some data, in which case you should not use the name config.

cwd

Type: string
Default: app.getPath('userData')

Storage file location. Don't specify this unless absolutely necessary! By default, it will pick the optimal location by adhering to system conventions. You are very likely to get this wrong and annoy users.

If a relative path, it's relative to the default cwd. For example, {cwd: 'unicorn'} would result in a storage file in ~/Library/Application Support/App Name/unicorn.

encryptionKey

Type: string | Buffer | TypedArray | DataView
Default: undefined

Note that this is not intended for security purposes, since the encryption key would be easily found inside a plain-text Node.js app.

Its main use is for obscurity. If a user looks through the config directory and finds the config file, since it's just a JSON file, they may be tempted to modify it. By providing an encryption key, the file will be obfuscated, which should hopefully deter any users from doing so.

When specified, the store will be encrypted using the aes-256-cbc encryption algorithm.

fileExtension

Type: string
Default: 'json'

Extension of the config file.

You would usually not need this, but could be useful if you want to interact with a file with a custom file extension that can be associated with your app. These might be simple save/export/preference files that are intended to be shareable or saved outside of the app.

clearInvalidConfig

Type: boolean
Default: false

The config is cleared if reading the config file causes a SyntaxError. This is a good behavior for unimportant data, as the config file is not intended to be hand-edited, so it usually means the config is corrupt and there's nothing the user can do about it anyway. However, if you let the user edit the config file directly, mistakes might happen and it could be more useful to throw an error when the config is invalid instead of clearing.

serialize

Type: Function
Default: value => JSON.stringify(value, null, '\t')

Function to serialize the config object to a UTF-8 string when writing the config file.

You would usually not need this, but it could be useful if you want to use a format other than JSON.

deserialize

Type: Function
Default: JSON.parse

Function to deserialize the config object from a UTF-8 string when reading the config file.

You would usually not need this, but it could be useful if you want to use a format other than JSON.

accessPropertiesByDotNotation

Type: boolean
Default: true

Accessing nested properties by dot notation. For example:

const Store = require('electron-store');

const store = new Store();

store.set({
	foo: {
		bar: {
			foobar: '��'
		}
	}
});

console.log(store.get('foo.bar.foobar'));
//=> '��'

Alternatively, you can set this option to false so the whole string would be treated as one key.

const store = new Store({accessPropertiesByDotNotation: false});

store.set({
	`foo.bar.foobar`: '��'
});

console.log(store.get('foo.bar.foobar'));
//=> '��'

watch

Type: boolean
Default: false

Watch for any changes in the config file and call the callback for onDidChange or onDidAnyChange if set. This is useful if there are multiple processes changing the same config file, for example, if you want changes done in the main process to be reflected in a renderer process.

Instance

You can use dot-notation in a key to access nested properties.

The instance is iterable so you can use it directly in a for…of loop.

.set(key, value)

Set an item.

The value must be JSON serializable. Trying to set the type undefined, function, or symbol will result in a TypeError.

.set(object)

Set multiple items at once.

.get(key, defaultValue?)

Get an item or defaultValue if the item does not exist.

.reset(...keys)

Reset items to their default values, as defined by the defaults or schema option.

Use .clear() to reset all items.

.has(key)

Check if an item exists.

.delete(key)

Delete an item.

.clear()

Delete all items.

This resets known items to their default values, if defined by the defaults or schema option.

.onDidChange(key, callback)

callback: (newValue, oldValue) => {}

Watches the given key, calling callback on any changes.

When a key is first set oldValue will be undefined, and when a key is deleted newValue will be undefined.

Returns a function which you can use to unsubscribe:

const unsubscribe = store.onDidChange(key, callback);

unsubscribe();

.onDidAnyChange(callback)

callback: (newValue, oldValue) => {}

Watches the whole config object, calling callback on any changes.

oldValue and newValue will be the config object before and after the change, respectively. You must compare oldValue to newValue to find out what changed.

Returns a function which you can use to unsubscribe:

const unsubscribe = store.onDidAnyChange(callback);

unsubscribe();

.size

Get the item count.

.store

Get all the data as an object or replace the current data with an object:

const Store = require('electron-store');

const store = new Store();

store.store = {
	hello: 'world'
};

.path

Get the path to the storage file.

.openInEditor()

Open the storage file in the user's editor.

initRenderer()

Initializer to set up the required ipc communication channels for the module when a Store instance is not created in the main process and you are creating a Store instance in the Electron renderer process only.

In the main process:

const Store = require('electron-store');

Store.initRenderer();

And in the renderer process:

const Store = require('electron-store');

const store = new Store();

store.set('unicorn', '��');
console.log(store.get('unicorn'));
//=> '��'

FAQ

Advantages over window.localStorage

Can I use YAML or another serialization format?

The serialize and deserialize options can be used to customize the format of the config file, as long as the representation is compatible with utf8 encoding.

Example using YAML:

const Store = require('electron-store');
const yaml = require('js-yaml');

const store = new Store({
	fileExtension: 'yaml',
	serialize: yaml.safeDump,
	deserialize: yaml.safeLoad
});

How do I get store values in the renderer process when my store was initialized in the main process?

The store is not a singleton, so you will need to either initialize the store in a file that is imported in both the main and renderer process, or you have to pass the values back and forth as messages. Electron provides a handy invoke/handle API that works well for accessing these values.

ipcMain.handle('getStoreValue', (event, key) => {
	return store.get(key);
});
const foo = await ipcRenderer.invoke('getStoreValue', 'foo');

Can I use it for large amounts of data?

This package is not a database. It simply uses a JSON file that is read/written on every change. Prefer using it for smaller amounts of data like user settings, value caching, state, etc.

If you need to store large blobs of data, I recommend saving it to disk and to use this package to store the path to the file instead.

Related

  • 有一个很奇怪的问题,我在网上好像都没有发现其他人遇到过。 使用localStorage保存一些数据,在windows系统中可以正常保存,但在linux中运行.exe程序重启后,保存的数据就丢失了,或是无法重新写入新数据。 找了很久都不知道是什么原因导致的,所以改用electron-store来储存数据。 1.使用eletron自带的cookie存储信息 var session = require(

  • Electron优缺点 优点 跨平台性好, 界面美观; 前端工程化 + 前端的第三方库(npm) + 前端生态 熟悉的语言(HTML/JS/CSS) + 环境(Node.js) 一次开发三平台可用 缺点:底层交互差,性能差,包大 基础概念 主进程 与 渲染进程 主进程使用BrowserWindow 创建实例 主进程销毁后,对应的渲染进程会被终止 主进程与渲染进程通过IPC方式(事件驱动)进行通信

  • Electron没有内置的方法来持久保存用户首选项和其他数据。使用electron-store模块可以帮助完成上述需求,专注于构建应用程序。数据保存在JSON文件中app.getPath(‘userData’)。 GitHub地址:https://github.com/sindresorhus/electron-store 安装 $ npm install electron-store --sav

  • Electron-store是一个基于Electron平台的数据存储库,可以帮助你简化在本地存储数据的过程。使用JSON文件作为配置是一种常见的方法,它可以方便的存储和读取数据。下面是使用electron-store将资源转移到本地的一般流程: 安装electron-store:使用npm安装electron-store库。 创建JSON文件:创建一个JSON文件,并为每个要存储的资源设置相应的键

  • npm安装: npm install electron-store yarn安装: yarn add electron-store 使用方法: const Store = require('electron-store'); const store = new Store(); //如果需要加密存储 就用下面的 //const store = new Store({encryptionKey:

  • 之前项目中遇到一个问题,使用了脚手架,并且引入了electron-store这个包。在开发模式下是能正常运行的,但是打包后却会包Cannot find module “.” 的问题,类似的issue在github的electron的上也有很多人提到,最终,在那个脚手架的issue下找到了答案 方法 //在根目录下 npm uninstall electron-store --save //卸载el

  • 自动升级的方式有很多种,我们公司第一版是使用fs做文件的下载和替换,但是存在C:// programfile的权限问题,因此只好更换技术方案。使用Electron-builder结合updater实现自动升级功能。 一、electron-builder的配置 在package.json中安装依赖 "devDependencies": { ... "electron": "^8.2.

  • 存储数据我并没有采用数据库方案,仅仅存储数量不多的简单数据也不至于动用数据库。这里选择的是electron-store作为主要存储工具,这个工具即使不作为主要存储工具仅存储用户启动项也是极好的。 安装electron-store,如果使用npm安装不成功则使用cnpm安装,总有一款适合你。 使用方法: const Store = require('electron-store'); const

  • elelctron-store elelctron-store 是很好的本地储存库 https://www.npmjs.com/package/electron-store 使用 npm i elelctron-store 设置 electron-vue 的运行环境 在项目根路径下新增 vue.config.js module.exports={ pluginOptions: {

  • 可能是没有进行electron-store的初始化 const Store = require('electron-store'); Store.initRenderer(); 目前的electron-store的版本 "electron-store": "^8.0.1"

 相关资料
  • Electron Electron / Electron Documentation Electron github / Electron github docs zh-CN Electron 是什么 Electron 是一个能让你通过 JavaScript、 HTML 和 CSS 构建桌面应用的库 。这些应用能打包到 Mac 、 Windows 和 Linux 电脑上运行,当然它们也能上架到 M

  • Electron 是一个使用 JavaScript、HTML 和 CSS 构建跨平台的桌面应用程序。它基于 Node.js 和 Chromium,被 Atom 编辑器和许多其他应用程序使用。 Electron 兼容 Mac、Windows 和 Linux,可以构建出三个平台的应用程序。

  • Package time feature toggles What are fuses? For a subset of Electron functionality it makes sense to disable certain features for an entire application. For example, 99% of apps don't make use of ELE

  • electron-vue 是一个基于 vue 来构造 electron 应用程序的样板代码。 概要 该项目的目的,是为了要避免使用 vue 手动建立起 electron 应用程序。electron-vue 充分利用 vue-cli 作为脚手架工具,加上拥有 vue-loader 的 webpack、electron-packager 或是 electron-builder,以及一些最常用的插件,如

  • 基于 Electron 桌面开发平台的自研应用框架 Sugar-Electron,期望能改善 Electron 应用稳定性和帮助开发团队降低开发和维护成本。 关于应用稳定性 Electron应用程序有三大基础模块: 主进程 渲染进程 进程间通信 由于我们属于多窗口(多渲染进程)的应用,所以我们会把窗口公共的服务模块都写到主进程模块,这为整个程序的稳定性埋下了隐患。 在Electron中,主进程控制

  • electron-player 是一个基于 electron-vue 的音视频播放器。 相关技术 electron:负责构建播放器的所需要的环境,提供访问系统资源的api(调用资源管理器,浏览器等等)以及打包成桌面应用程序 vue:负责构建播放器的界面 node:负责处理文件和路径问题,主要使用fs和path这2个模块 express:负责把视频读取出来,把视频以流的形式返回 html5相关技术: