├── .editorconfig ├── .gitattributes ├── .github └── workflows │ └── main.yml ├── .gitignore ├── .npmrc ├── fixture-cwd.js ├── fixture.js ├── index.d.ts ├── index.js ├── index.test-d.ts ├── license ├── package.json ├── readme.md └── test.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | [*.yml] 11 | indent_style = space 12 | indent_size = 2 13 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | - push 4 | - pull_request 5 | jobs: 6 | test: 7 | name: Node.js ${{ matrix.node-version }} 8 | runs-on: macos-latest 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | node-version: 13 | - 20 14 | steps: 15 | - uses: actions/checkout@v4 16 | - uses: actions/setup-node@v4 17 | with: 18 | node-version: ${{ matrix.node-version }} 19 | - run: npm install 20 | - run: npm test 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | yarn.lock 3 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /fixture-cwd.js: -------------------------------------------------------------------------------- 1 | import process from 'node:process'; 2 | import path from 'node:path'; 3 | import electron from 'electron'; 4 | import Store from './index.js'; 5 | 6 | // Prevent Electron from never exiting when an exception happens 7 | process.on('uncaughtException', error => { 8 | console.error('Exception:', error); 9 | process.exit(1); 10 | }); 11 | 12 | console.log(electron.app.getPath('userData')); 13 | 14 | const store = new Store({cwd: 'foo'}); 15 | store.set('unicorn', '🦄'); 16 | console.log(store.path); 17 | 18 | const store2 = new Store({cwd: path.join(import.meta.dirname, 'bar')}); 19 | store2.set('ava', '🚀'); 20 | console.log(store2.path); 21 | 22 | electron.app.quit(); 23 | -------------------------------------------------------------------------------- /fixture.js: -------------------------------------------------------------------------------- 1 | import process from 'node:process'; 2 | import assert from 'node:assert'; 3 | import electron from 'electron'; 4 | import Store from './index.js'; 5 | 6 | // Prevent Electron from never exiting when an exception happens 7 | process.on('uncaughtException', error => { 8 | console.error('Exception:', error); 9 | process.exit(1); 10 | }); 11 | 12 | const store = new Store({name: 'electron-store'}); 13 | 14 | const storeWithSchema = new Store({ 15 | name: 'electron-store-with-schema', 16 | schema: { 17 | foo: { 18 | default: 42, 19 | }, 20 | }, 21 | }); 22 | 23 | store.set('unicorn', '🦄'); 24 | assert.strictEqual(store.get('unicorn'), '🦄'); 25 | 26 | store.delete('unicorn'); 27 | assert.strictEqual(store.get('unicorn'), undefined); 28 | 29 | storeWithSchema.set('foo', 77); 30 | assert.strictEqual(storeWithSchema.get('foo'), 77); 31 | 32 | storeWithSchema.reset('foo'); 33 | assert.strictEqual(storeWithSchema.get('foo'), 42); 34 | 35 | // To be checked in AVA 36 | store.set('ava', '🚀'); 37 | 38 | console.log(store.path); 39 | 40 | electron.app.quit(); 41 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | import {type Except} from 'type-fest'; 2 | import Conf, {type Options as ConfigOptions} from 'conf'; 3 | 4 | export {Schema} from 'conf'; 5 | 6 | export type Options> = Except, 'configName' | 'projectName' | 'projectVersion' | 'projectSuffix'> & { 7 | /** 8 | Name of the storage file (without extension). 9 | 10 | 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`. 11 | 12 | @default 'config' 13 | */ 14 | readonly name?: string; 15 | }; 16 | 17 | /** 18 | Simple data persistence for your [Electron](https://electronjs.org) app or module - Save and load user settings, app state, cache, etc. 19 | */ 20 | export default class ElectronStore = Record> extends Conf { 21 | /** 22 | 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. 23 | */ 24 | static initRenderer(): void; 25 | 26 | /** 27 | Changes are written to disk atomically, so if the process crashes during a write, it will not corrupt the existing store. 28 | 29 | @example 30 | ``` 31 | import Store from 'electron-store'; 32 | 33 | type StoreType = { 34 | isRainbow: boolean, 35 | unicorn?: string 36 | } 37 | 38 | const store = new Store({ 39 | defaults: { 40 | isRainbow: true 41 | } 42 | }); 43 | 44 | store.get('isRainbow'); 45 | //=> true 46 | 47 | store.set('unicorn', '🦄'); 48 | console.log(store.get('unicorn')); 49 | //=> '🦄' 50 | 51 | store.delete('unicorn'); 52 | console.log(store.get('unicorn')); 53 | //=> undefined 54 | ``` 55 | */ 56 | constructor(options?: Options); 57 | 58 | /** 59 | Open the storage file in the user's editor. 60 | 61 | Returns a promise that resolves when the editor has been opened, or rejects if it failed to open. 62 | */ 63 | openInEditor(): Promise; 64 | } 65 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import process from 'node:process'; 2 | import path from 'node:path'; 3 | import electron from 'electron'; 4 | import Conf from 'conf'; 5 | 6 | const {app, ipcMain, shell} = electron; 7 | 8 | let isInitialized = false; 9 | 10 | // Set up the `ipcMain` handler for communication between renderer and main process. 11 | const initDataListener = () => { 12 | if (!ipcMain || !app) { 13 | throw new Error('Electron Store: You need to call `.initRenderer()` from the main process.'); 14 | } 15 | 16 | const appData = { 17 | defaultCwd: app.getPath('userData'), 18 | appVersion: app.getVersion(), 19 | }; 20 | 21 | if (isInitialized) { 22 | return appData; 23 | } 24 | 25 | ipcMain.on('electron-store-get-data', event => { 26 | event.returnValue = appData; 27 | }); 28 | 29 | isInitialized = true; 30 | 31 | return appData; 32 | }; 33 | 34 | export default class ElectronStore extends Conf { 35 | constructor(options) { 36 | let defaultCwd; 37 | let appVersion; 38 | 39 | // If we are in the renderer process, we communicate with the main process 40 | // to get the required data for the module otherwise, we pull from the main process. 41 | if (process.type === 'renderer') { 42 | const appData = electron.ipcRenderer.sendSync('electron-store-get-data'); 43 | 44 | if (!appData) { 45 | throw new Error('Electron Store: You need to call `.initRenderer()` from the main process.'); 46 | } 47 | 48 | ({defaultCwd, appVersion} = appData); 49 | } else if (ipcMain && app) { 50 | ({defaultCwd, appVersion} = initDataListener()); 51 | } 52 | 53 | options = { 54 | name: 'config', 55 | ...options, 56 | }; 57 | 58 | options.projectVersion ||= appVersion; 59 | 60 | if (options.cwd) { 61 | options.cwd = path.isAbsolute(options.cwd) ? options.cwd : path.join(defaultCwd, options.cwd); 62 | } else { 63 | options.cwd = defaultCwd; 64 | } 65 | 66 | options.configName = options.name; 67 | delete options.name; 68 | 69 | super(options); 70 | } 71 | 72 | static initRenderer() { 73 | initDataListener(); 74 | } 75 | 76 | async openInEditor() { 77 | const error = await shell.openPath(this.path); 78 | 79 | if (error) { 80 | throw new Error(error); 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /index.test-d.ts: -------------------------------------------------------------------------------- 1 | import {expectType, expectAssignable} from 'tsd'; 2 | import Store, {Schema} from './index.js'; 3 | 4 | new Store({defaults: {}}); // eslint-disable-line no-new 5 | new Store({name: 'myConfiguration'}); // eslint-disable-line no-new 6 | 7 | const store = new Store(); 8 | 9 | store.set('foo', 'bar'); 10 | store.set({ 11 | foo: 'bar', 12 | foo2: 'bar2', 13 | }); 14 | store.delete('foo'); 15 | store.get('foo'); 16 | store.get('foo', 42); 17 | store.reset('foo'); 18 | store.has('foo'); 19 | store.clear(); 20 | 21 | await store.openInEditor(); 22 | 23 | store.size; // eslint-disable-line @typescript-eslint/no-unused-expressions 24 | store.store; // eslint-disable-line @typescript-eslint/no-unused-expressions 25 | 26 | store.store = { 27 | foo: 'bar', 28 | }; 29 | 30 | store.path; // eslint-disable-line @typescript-eslint/no-unused-expressions 31 | 32 | type TypedStore = { 33 | isEnabled: boolean; 34 | interval: number; 35 | }; 36 | 37 | const typedStore = new Store({ 38 | defaults: { 39 | isEnabled: true, 40 | interval: 30_000, 41 | }, 42 | }); 43 | 44 | expectType(typedStore.get('interval')); 45 | 46 | const isEnabled = false; 47 | typedStore.set('isEnabled', isEnabled); 48 | typedStore.set({ 49 | isEnabled: true, 50 | interval: 10_000, 51 | }); 52 | 53 | // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment 54 | const offDidChange = typedStore.onDidChange( 55 | 'isEnabled', 56 | (newValue, oldValue) => { 57 | expectType(newValue); 58 | expectType(oldValue); 59 | }, 60 | ); 61 | 62 | expectAssignable<() => void>(offDidChange); 63 | offDidChange(); 64 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Sindre Sorhus (https://sindresorhus.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "electron-store", 3 | "version": "10.0.1", 4 | "description": "Simple data persistence for your Electron app or module - Save and load user settings, app state, cache, etc", 5 | "license": "MIT", 6 | "repository": "sindresorhus/electron-store", 7 | "funding": "https://github.com/sponsors/sindresorhus", 8 | "author": { 9 | "name": "Sindre Sorhus", 10 | "email": "sindresorhus@gmail.com", 11 | "url": "https://sindresorhus.com" 12 | }, 13 | "type": "module", 14 | "exports": { 15 | "types": "./index.d.ts", 16 | "default": "./index.js" 17 | }, 18 | "sideEffects": false, 19 | "engines": { 20 | "node": ">=20" 21 | }, 22 | "scripts": { 23 | "test": "xo && ava && tsd" 24 | }, 25 | "files": [ 26 | "index.js", 27 | "index.d.ts" 28 | ], 29 | "keywords": [ 30 | "electron", 31 | "store", 32 | "app", 33 | "config", 34 | "storage", 35 | "conf", 36 | "configuration", 37 | "settings", 38 | "preferences", 39 | "json", 40 | "data", 41 | "persist", 42 | "persistent", 43 | "save" 44 | ], 45 | "dependencies": { 46 | "conf": "^13.0.0", 47 | "type-fest": "^4.20.0" 48 | }, 49 | "devDependencies": { 50 | "ava": "^6.1.3", 51 | "electron": "^31.0.1", 52 | "execa": "^9.2.0", 53 | "tsd": "^0.31.0", 54 | "xo": "^0.58.0" 55 | }, 56 | "xo": { 57 | "envs": [ 58 | "node", 59 | "browser" 60 | ] 61 | }, 62 | "tsd": { 63 | "compilerOptions": { 64 | "module": "node16", 65 | "moduleResolution": "node16", 66 | "moduleDetection": "force" 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # electron-store 2 | 3 | > Simple data persistence for your [Electron](https://electronjs.org) app or module - Save and load user settings, app state, cache, etc 4 | 5 | Electron doesn't have a built-in way to persist user settings 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')`](https://electronjs.org/docs/api/app#appgetpathname). 6 | 7 | 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. 8 | 9 | ## Install 10 | 11 | ```sh 12 | npm install electron-store 13 | ``` 14 | 15 | *Requires Electron 30 or later.* 16 | 17 | > [!NOTE] 18 | > This package is native [ESM](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) and no longer provides a CommonJS export. If your project uses CommonJS, you will have to [convert to ESM](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c). More info about [Electron and ESM](https://www.electronjs.org/docs/latest/tutorial/esm). Please don't open issues for questions regarding CommonJS and ESM. 19 | 20 | ## Usage 21 | 22 | ```js 23 | import Store from 'electron-store'; 24 | 25 | const store = new Store(); 26 | 27 | store.set('unicorn', '🦄'); 28 | console.log(store.get('unicorn')); 29 | //=> '🦄' 30 | 31 | // Use dot-notation to access nested properties 32 | store.set('foo.bar', true); 33 | console.log(store.get('foo')); 34 | //=> {bar: true} 35 | 36 | store.delete('unicorn'); 37 | console.log(store.get('unicorn')); 38 | //=> undefined 39 | ``` 40 | 41 | ## API 42 | 43 | Changes are written to disk atomically, so if the process crashes during a write, it will not corrupt the existing config. 44 | 45 | ### Store(options?) 46 | 47 | Returns a new instance. 48 | 49 | ### options 50 | 51 | Type: `object` 52 | 53 | #### defaults 54 | 55 | Type: `object` 56 | 57 | Default values for the store items. 58 | 59 | **Note:** The values in `defaults` will overwrite the `default` key in the `schema` option. 60 | 61 | #### schema 62 | 63 | type: `object` 64 | 65 | [JSON Schema](https://json-schema.org) to validate your config data. 66 | 67 | Under the hood, the JSON Schema validator [ajv](https://ajv.js.org/json-schema.html) is used to validate your config. We use [JSON Schema draft-2020-12](https://json-schema.org/draft/2020-12/release-notes) and support all validation keywords and formats. 68 | 69 | 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](https://json-schema.org/understanding-json-schema/reference/object.html#properties). 70 | 71 | Example: 72 | 73 | ```js 74 | import Store from 'electron-store'; 75 | 76 | const schema = { 77 | foo: { 78 | type: 'number', 79 | maximum: 100, 80 | minimum: 1, 81 | default: 50 82 | }, 83 | bar: { 84 | type: 'string', 85 | format: 'url' 86 | } 87 | }; 88 | 89 | const store = new Store({schema}); 90 | 91 | console.log(store.get('foo')); 92 | //=> 50 93 | 94 | store.set('foo', '1'); 95 | // [Error: Config schema violation: `foo` should be number] 96 | ``` 97 | 98 | **Note:** The `default` value will be overwritten by the `defaults` option if set. 99 | 100 | #### migrations 101 | 102 | Type: `object` 103 | 104 | **Important: I cannot provide support for this feature. It has some known bugs. I have no plans to work on it, but pull requests are welcome.** 105 | 106 | You can use migrations to perform operations to the store whenever a version is upgraded. 107 | 108 | The `migrations` object should consist of a key-value pair of `'version': handler`. The `version` can also be a [semver range](https://github.com/npm/node-semver#ranges). 109 | 110 | Example: 111 | 112 | ```js 113 | import Store from 'electron-store'; 114 | 115 | const store = new Store({ 116 | migrations: { 117 | '0.0.1': store => { 118 | store.set('debugPhase', true); 119 | }, 120 | '1.0.0': store => { 121 | store.delete('debugPhase'); 122 | store.set('phase', '1.0.0'); 123 | }, 124 | '1.0.2': store => { 125 | store.set('phase', '1.0.2'); 126 | }, 127 | '>=2.0.0': store => { 128 | store.set('phase', '>=2.0.0'); 129 | } 130 | } 131 | }); 132 | ``` 133 | 134 | ### beforeEachMigration 135 | 136 | Type: `Function`\ 137 | Default: `undefined` 138 | 139 | The given callback function will be called before each migration step. 140 | 141 | The function receives the store as the first argument and a context object as the second argument with the following properties: 142 | 143 | - `fromVersion` - The version the migration step is being migrated from. 144 | - `toVersion` - The version the migration step is being migrated to. 145 | - `finalVersion` - The final version after all the migrations are applied. 146 | - `versions` - All the versions with a migration step. 147 | 148 | This can be useful for logging purposes, preparing migration data, etc. 149 | 150 | Example: 151 | 152 | ```js 153 | import Store from 'electron-store'; 154 | 155 | console.log = someLogger.log; 156 | 157 | const mainConfig = new Store({ 158 | beforeEachMigration: (store, context) => { 159 | console.log(`[main-config] migrate from ${context.fromVersion} → ${context.toVersion}`); 160 | }, 161 | migrations: { 162 | '0.4.0': store => { 163 | store.set('debugPhase', true); 164 | } 165 | } 166 | }); 167 | 168 | const secondConfig = new Store({ 169 | beforeEachMigration: (store, context) => { 170 | console.log(`[second-config] migrate from ${context.fromVersion} → ${context.toVersion}`); 171 | }, 172 | migrations: { 173 | '1.0.1': store => { 174 | store.set('debugPhase', true); 175 | } 176 | } 177 | }); 178 | ``` 179 | 180 | #### name 181 | 182 | Type: `string`\ 183 | Default: `'config'` 184 | 185 | Name of the storage file (without extension). 186 | 187 | 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`. 188 | 189 | #### cwd 190 | 191 | Type: `string`\ 192 | Default: [`app.getPath('userData')`](https://electronjs.org/docs/api/app#appgetpathname) 193 | 194 | 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.* 195 | 196 | 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`. 197 | 198 | #### encryptionKey 199 | 200 | Type: `string | Buffer | TypedArray | DataView`\ 201 | Default: `undefined` 202 | 203 | Note that this is **not intended for security purposes**, since the encryption key would be easily found inside a plain-text Node.js app. 204 | 205 | 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. 206 | 207 | When specified, the store will be encrypted using the [`aes-256-cbc`](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation) encryption algorithm. 208 | 209 | #### fileExtension 210 | 211 | Type: `string`\ 212 | Default: `'json'` 213 | 214 | Extension of the config file. 215 | 216 | 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. 217 | 218 | #### clearInvalidConfig 219 | 220 | Type: `boolean`\ 221 | Default: `false` 222 | 223 | 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. 224 | 225 | #### serialize 226 | 227 | Type: `Function`\ 228 | Default: `value => JSON.stringify(value, null, '\t')` 229 | 230 | Function to serialize the config object to a UTF-8 string when writing the config file. 231 | 232 | You would usually not need this, but it could be useful if you want to use a format other than JSON. 233 | 234 | #### deserialize 235 | 236 | Type: `Function`\ 237 | Default: `JSON.parse` 238 | 239 | Function to deserialize the config object from a UTF-8 string when reading the config file. 240 | 241 | You would usually not need this, but it could be useful if you want to use a format other than JSON. 242 | 243 | #### accessPropertiesByDotNotation 244 | 245 | Type: `boolean`\ 246 | Default: `true` 247 | 248 | Accessing nested properties by dot notation. For example: 249 | 250 | ```js 251 | import Store from 'electron-store'; 252 | 253 | const store = new Store(); 254 | 255 | store.set({ 256 | foo: { 257 | bar: { 258 | foobar: '🦄' 259 | } 260 | } 261 | }); 262 | 263 | console.log(store.get('foo.bar.foobar')); 264 | //=> '🦄' 265 | ``` 266 | 267 | Alternatively, you can set this option to `false` so the whole string would be treated as one key. 268 | 269 | ```js 270 | const store = new Store({accessPropertiesByDotNotation: false}); 271 | 272 | store.set({ 273 | `foo.bar.foobar`: '🦄' 274 | }); 275 | 276 | console.log(store.get('foo.bar.foobar')); 277 | //=> '🦄' 278 | ``` 279 | 280 | #### watch 281 | 282 | Type: `boolean`\ 283 | Default: `false` 284 | 285 | 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. 286 | 287 | ### Instance 288 | 289 | You can use [dot-notation](https://github.com/sindresorhus/dot-prop) in a `key` to access nested properties. 290 | 291 | The instance is [`iterable`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Iteration_protocols) so you can use it directly in a [`for…of`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of) loop. 292 | 293 | #### .set(key, value) 294 | 295 | Set an item. 296 | 297 | The `value` must be JSON serializable. Trying to set the type `undefined`, `function`, or `symbol` will result in a TypeError. 298 | 299 | #### .set(object) 300 | 301 | Set multiple items at once. 302 | 303 | #### .get(key, defaultValue?) 304 | 305 | Get an item or `defaultValue` if the item does not exist. 306 | 307 | #### .reset(...keys) 308 | 309 | Reset items to their default values, as defined by the `defaults` or `schema` option. 310 | 311 | Use `.clear()` to reset all items. 312 | 313 | #### .has(key) 314 | 315 | Check if an item exists. 316 | 317 | #### .delete(key) 318 | 319 | Delete an item. 320 | 321 | #### .clear() 322 | 323 | Delete all items. 324 | 325 | This resets known items to their default values, if defined by the `defaults` or `schema` option. 326 | 327 | #### .onDidChange(key, callback) 328 | 329 | `callback`: `(newValue, oldValue) => {}` 330 | 331 | Watches the given `key`, calling `callback` on any changes. 332 | 333 | When a key is first set `oldValue` will be `undefined`, and when a key is deleted `newValue` will be `undefined`. 334 | 335 | Returns a function which you can use to unsubscribe: 336 | 337 | ```js 338 | const unsubscribe = store.onDidChange(key, callback); 339 | 340 | unsubscribe(); 341 | ``` 342 | 343 | #### .onDidAnyChange(callback) 344 | 345 | `callback`: `(newValue, oldValue) => {}` 346 | 347 | Watches the whole config object, calling `callback` on any changes. 348 | 349 | `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. 350 | 351 | Returns a function which you can use to unsubscribe: 352 | 353 | ```js 354 | const unsubscribe = store.onDidAnyChange(callback); 355 | 356 | unsubscribe(); 357 | ``` 358 | 359 | #### .size 360 | 361 | Get the item count. 362 | 363 | #### .store 364 | 365 | Get all the data as an object or replace the current data with an object: 366 | 367 | ```js 368 | import Store from 'electron-store'; 369 | 370 | const store = new Store(); 371 | 372 | store.store = { 373 | hello: 'world' 374 | }; 375 | ``` 376 | 377 | #### .path 378 | 379 | Get the path to the storage file. 380 | 381 | #### .openInEditor() 382 | 383 | Open the storage file in the user's editor. 384 | 385 | Returns a promise that resolves when the editor has been opened, or rejects if it failed to open. 386 | 387 | ### initRenderer() 388 | 389 | 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. 390 | 391 | In the main process: 392 | 393 | ```js 394 | import Store from 'electron-store'; 395 | 396 | Store.initRenderer(); 397 | ``` 398 | 399 | And in the renderer process: 400 | 401 | ```js 402 | import Store from 'electron-store'; 403 | 404 | const store = new Store(); 405 | 406 | store.set('unicorn', '🦄'); 407 | console.log(store.get('unicorn')); 408 | //=> '🦄' 409 | ``` 410 | 411 | ## FAQ 412 | 413 | #### [Advantages over `window.localStorage`](https://github.com/sindresorhus/electron-store/issues/17) 414 | 415 | #### Can I use YAML or another serialization format? 416 | 417 | 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. 418 | 419 | Example using YAML: 420 | 421 | ```js 422 | import Store from 'electron-store'; 423 | import yaml from 'js-yaml'; 424 | 425 | const store = new Store({ 426 | fileExtension: 'yaml', 427 | serialize: yaml.safeDump, 428 | deserialize: yaml.safeLoad 429 | }); 430 | ``` 431 | 432 | #### How do I get store values in the renderer process when my store was initialized in the main process? 433 | 434 | 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](https://github.com/sindresorhus/electron-store/issues/15), or you have to pass the values back and forth as messages. Electron provides a handy [`invoke/handle` API](https://www.electronjs.org/docs/api/ipc-main#ipcmainhandlechannel-listener) that works well for accessing these values. 435 | 436 | ```js 437 | ipcMain.handle('getStoreValue', (event, key) => { 438 | return store.get(key); 439 | }); 440 | ``` 441 | 442 | ```js 443 | const foo = await ipcRenderer.invoke('getStoreValue', 'foo'); 444 | ``` 445 | 446 | #### Can I use it for large amounts of data? 447 | 448 | 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. 449 | 450 | 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. 451 | 452 | ## Related 453 | 454 | - [electron-util](https://github.com/sindresorhus/electron-util) - Useful utilities for developing Electron apps and modules 455 | - [electron-debug](https://github.com/sindresorhus/electron-debug) - Adds useful debug features to your Electron app 456 | - [electron-context-menu](https://github.com/sindresorhus/electron-context-menu) - Context menu for your Electron app 457 | - [electron-dl](https://github.com/sindresorhus/electron-dl) - Simplified file downloads for your Electron app 458 | - [electron-unhandled](https://github.com/sindresorhus/electron-unhandled) - Catch unhandled errors and promise rejections in your Electron app 459 | - [electron-reloader](https://github.com/sindresorhus/electron-reloader) - Simple auto-reloading for Electron apps during development 460 | - [electron-serve](https://github.com/sindresorhus/electron-serve) - Static file serving for Electron apps 461 | - [conf](https://github.com/sindresorhus/conf) - Simple config handling for your app or module 462 | - [More…](https://github.com/search?q=user%3Asindresorhus+electron) 463 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | import fs from 'node:fs'; 2 | import path from 'node:path'; 3 | import electron from 'electron'; 4 | import test from 'ava'; 5 | import {execa} from 'execa'; 6 | 7 | // See https://github.com/sindresorhus/conf for more extensive tests 8 | 9 | const run = async file => { 10 | const {stdout} = await execa(electron, [file], { 11 | env: { 12 | ELECTRON_ENABLE_LOGGING: true, 13 | ELECTRON_ENABLE_STACK_DUMPING: true, 14 | ELECTRON_NO_ATTACH_CONSOLE: true, 15 | }, 16 | }); 17 | 18 | return stdout.trim(); 19 | }; 20 | 21 | test('main', async t => { 22 | const storagePath = await run('fixture.js'); 23 | t.deepEqual(JSON.parse(fs.readFileSync(storagePath, 'utf8')), {ava: '🚀'}); 24 | fs.unlinkSync(storagePath); 25 | }); 26 | 27 | test('cwd option', async t => { 28 | const result = await run('fixture-cwd.js'); 29 | const [defaultPath, storagePath, storagePath2] = result.split('\n'); 30 | t.is(storagePath, path.join(defaultPath, 'foo/config.json')); 31 | t.is(storagePath2, path.join(import.meta.dirname, 'bar/config.json')); 32 | fs.unlinkSync(storagePath); 33 | fs.unlinkSync(storagePath2); 34 | }); 35 | --------------------------------------------------------------------------------