sindresorhus / electron-store Goto Github PK
View Code? Open in Web Editor NEWSimple data persistence for your Electron app or module - Save and load user preferences, app state, cache, etc
License: MIT License
Simple data persistence for your Electron app or module - Save and load user preferences, app state, cache, etc
License: MIT License
Would be useful to have forward migration support built-in. You define the version when something changed and a function where you can manipulate the store and the correct migrations will be applied according to the installed version on the first run after an update.
Quick braindump API:
const Store = require('electron-store');
const migrations = {
'1.0.0': store => {
const old = store.get('old');
store.set('new', old);
store.delete('old');
}
};
const store = new Store({migrations});
I'm open to feedback.
const items: [
{'data1':true},
{'data2':false}
]
How can I config.set('items[0].data1',false)?
Currently, I do config.get('items') and loop through updating the values and then doing config.set('items') which works but feels backward.
On macOS the database is located there: ~/Library/Application Support/App Name
but what about Windows?
I think it could be useful to be able to observe changes. I like how it's done in Atom.
Previous art:
Is not clean how to use with Typescript. Here is the typings definition: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/electron-store any help is much apprecciated!
Hi,
Is it possible to give an example on how to use the package after packaging the app with electron-packager ?
(I guess it is in asar archive)
Thanks
The examples show setting objects. What are all the kinds of values that this projects supports?
You said in your readme that encryptionKey is not meant for security. But what if I prompt user everytime the app is opened for encryptionKey and never store it in App's code itself, will that be secured enough?
What is the maximum file size we can store in this. Can i store 100MB file
You close and lock issues but they arent resolved - this doesnt work with webpack. Locking the issue so no one can post in it and provide solutions only makes the issue far worse. Asking to just go ask in webpack doesnt help solve the problem when people run into it and is EXTREMELY upsetting and annoying. If you didn't lock it to purposefully make it hard to fix this issue then perhaps people would have provided more solutions to find one that works for everyone...
Been using this module for a while, and working great. But data loss occurs when the app hangs or is quit forcefully. Any workaround or solutions for the issue ?
If I require this module in webpack, it will break webpack because of this line
const parentDir = path.dirname(module.parent.filename);
Is there any way to make it work webpack, maybe refer to the global.module instead of just module?
I'm using:
Just tried the default usage from the readme. I get this error:
/Users/yann/Development/electron-config-test/node_modules/electron-config/index.js:8
opts.cwd = (electron.app || electron.remote.app).getPath('userData');
^
TypeError: Cannot read property 'app' of undefined
at ElectronConfig (/Users/yann/Development/electron-config-test/node_modules/electron-config/index.js:8:46)
at Object.<anonymous> (/Users/yann/Development/electron-config-test/index.js:3:16)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
By the way, why is not electron
a dependency in electron-config
(got Cannot find module 'electron'
error when electron not installed)?
https://gist.github.com/yannbertrand/c2f6f246df2c35e45a2bba7237688da3
[email protected]
[email protected]
I am doing this
store = new Store({
name : 'encrypted_config',
encryptionKey : 'test123',
});
When the app restarts and I try to do this
store = new Store({
name : 'encrypted_config',
encryptionKey : 'xyz123',
});
it just creates a new file instead of throwing error or something, am I missing something?
I am using electron-store to re-hydrate the state of my redux store on app load. I am noticing that the setters and getters on store properties are showing up in my redux store. Is there an easy way to get values out of the store as properties that way I can keep my store pure and serializable?
I know that I can JSON.stringify()
and then JSON.parse()
to get rid of the getters and setters but that seems kind of inefficient? Any help on answering this would be appreciated!
What I've known is to get and append and set .
list = store.get('list')
list.push(foo)
store.set('list', list)
Is this the only way?
Any shortcuts like store.push('list', foo)
Thanks~
I am using Electron and React to create a web app, and the documentation for electron-config does not show how to carry out IPC (inter-process communication) between processes.
In the case of React, the render process would be a component. How do I use electron-config with my React component and send the user data over to the main Electron process?
Thanks
Uncaught Error: Cannot find module "."
at webpackMissingModule (index.js:25)
at ElectronStore.Conf (index.js:25)
at ElectronStore (index.js:20)
at Object../app/actions/recent-projects.js (recent-projects.js:4)
at __webpack_require__ (bootstrap 92e2fd3…:677)
at fn (bootstrap 92e2fd3…:87)
at Object../app/containers/HomePage.js (HomePage.js:8)
at __webpack_require__ (bootstrap 92e2fd3…:677)
at fn (bootstrap 92e2fd3…:87)
at Object../app/routes.js (routes.js:5)
Have this error in one of my project. Unluckily, I cannot provide the source code.
Would be nice if you could store.set('foo', new Date())
and get back a Date
object when you do store.get('foo')
. Could probably make use of the second argument to JSON.parse()
. We need to save some kind of information to indicate that it's a native Date format. Maybe a separate __meta__
key or something. Suggestions welcome.
This may be out of scope for the intended purpose of the module. Currently you can't override the extension used, just the name and location. With the move to a more generic name (#4) to represent a larger use case for this module, does it make sense to allow overriding the extension?
For example, I could use electron-store
to interact with a file with a custom file extension that can be associated with my electron app. These might be simple save/export/preference files that are intended to be shareable or saved outside of the application. It may still be a json
file or an "encrypted" json
file, but the user need not know that.
IMHO, this package can be used for either the config or just for saving/caching data (like we're doing it in Now Desktop). Because of this, I recommend renaming it.
My suggestion is "electron-store" (the package name is available on npm).
Hi,
I'm using the electron-vue boilerplate.
When I add the line const Config = require('electron-config');
I get the following error:
Failed to compile.
./~/conf/index.js
21:27-43 Critical dependency: the request of a dependency is an expression
Any idea why?
Thanks
Have been using electron store in mac perfectly, but when packaged for windows it randomly throws this error:
When you click ok it carries on absolutely fine.
It seems windows doesn't let you store.set anything new during some processes... it looks to coincide with writing files with node.js but I can't be sure, does it 'lock' the config.json file at any point for any reason? Does this make sense to anyone? I'm really stuck on this and don't want to replace electron.store as a last resort as it's perfect otherwise!
Store file is not being encrypted.
Here is an example to help you visualize the issue:
var store = new Store({
name: "myExample",
encryptionKey: "oiV32mVp5lOwYneFESjrWq2xFByNOvNj"
})
store.set("this_is_a_key", "this_is_a_value")
And the result, a non-encrypted store file:
{
"this_is_a_key": "this_is_a_value"
}
Refer to this issue for more information: #26
Hello,
when doing the following, this is what I get:
import Config from 'electron-config';
const config = new Config({ 'locale': "en-US" });
console.log(config.get('locale'));
// ==> undefined
console.log(config.store);
// ==> {}
Why is that? Am I doing something wrong perhaps?
Thank you.
Hi,
I'm trying to build app using electron config but I have trouble with npm run package
using this module.
$ git clone https://github.com/chentsulin/electron-react-boilerplate
$ cd electron-react-boilerplate
$ npm run dev # GOOD
$ npm run package # GOOD
$ # Import electron-config
$ git diff
--- a/app/main.development.js
+++ b/app/main.development.js
@@ -1,4 +1,5 @@
import { app, BrowserWindow, Menu, shell } from 'electron';
+import Config from 'electron-config'
let menu;
let template;
$ npm run dev # GOOD
$ npm run package # FAILS (both on windows and linux)
# Uncaught Exception:
# TypeError: Cannot read prperty 'filename' of undefined
There is a substantial overlap between sindresorhus/electron-config and sindresorhus/conf, not the least of they being by the same author.
(There is also a yeoman/configstore project, but it appears deprecated. Is that correct?)
Hi, I was just wondering if there is a way to set electron store to use the full CR+LF windows line ends, so that my application users can open the files in Notepad? (currently it uses unix line ends so the file doesn't display properly unless they use an IDE/Notepad++ etc). Thanks if you can help!
Is there a way I can append an item to a list that is stored? For example:
store.set("listOfItems", [{ "name" : "John"}])
how would I then add another item to store.get("listOfItems")
thanks for any help from anyone
Your lib looks perfect to me, but I need possibility to set where config should be saved (basically app is for devs and i need some .rc file in ~ so it can persist after update & allow someone to edit it quickly). Is it hard to make?
Also it could be nice if I can pass json object in a store constructor as a first state, so I can actually manually sync data to file as a "backup" config
Like the title says.
Could this be done with node's events
without too much effort? Or could there be a way to easily implement onChange
event hooks?
I think a great enhancement would be the ability to override values with env vars. This would give us the ability to use the store as the single source of truth in out app. Today in order to do this we will need to abstract out a layer and have an object as our single source of truth and load items into this object (either by electron-store or env vars). Because of this we lose the ability to listen to onChange events which is a fantastic feature of the library.
I propose adding some convenience methods to make common things easier.
What I do most of the time when using electron-store
is to get a boolean and invert it. For example, store.set('isFoo', !store.get('isFoo'))
.
Would be nice to have:
.toggleBoolean(key)
which accepts a key and toggles the boolean..appendToArray(key, newItem)
which pushes a new item to the array. (#32).modify(key, mutateCallback)
which would give you a callback to modify the value that you then return in the callback:Before:
const array = store.get('array');
array.find(element => element.title === 'baz').src = 'something';
store.set('array', array);
After:
store.modify('array', array => {
array.find(element => element.title === 'baz').src = 'something';
return array;
});
These methods will require you to specify the key
in the defaults
option, so it would always work. If you try to use toggleBoolean()
and the underlaying value is of a different type, it would throw an error.
Any other convenience methods we could add? I'm also interested in feedback on the method names.
*Note: While I opened the issue here, the methods we eventually go for should be added to conf
.
I have some webapps that need to be converted into desktop app. Is there any plan to add feature for synchronize data with localStorage?
It seems if I want to run multiple instances of one app with different data configs. It would write into the same config.json file. Is there a recommended way of using it with multiple instances, or using something else?
I've supplied an encryption key when creating a new store, but nothing happens. Could you please elaborate on whats required / how this works?
Can be useful to ensure you only set the correct types in your config, and could validate if the config file is manually edited by the user.
https://github.com/epoberezkin/ajv looks like the best one.
Thoughts? Would you use this?
Note: This should be implemented in conf
first.
yaodingyd earned $100.00 by resolving this issue!
- Checkout the Issuehunt explorer to discover more funded issues.
- Need some help from other developers? Add your repositories on Issuehunt to raise funds.
I've got two windows open. One of them changes the state object.
store.set('preferences', newPrefs)
document.addEventListener('DOMContentLoaded', () => {
store.onDidChange('preferences', (newValue, oldValue) => {
console.log('hello from setting window', newValue, oldValue)
// works!
})
})
Another open window is also subscribed to the event, but it doesn't fire:
document.addEventListener('DOMContentLoaded', () => {
store.onDidChange('preferences', (newValue, oldValue) => {
console.log('hello from receiving window', newValue, oldValue)
// does not work :[
})
})
Hi,
I recently upgraded my application to version 1.3.0 of the library and the following initialization fails:
const store = new Store({
name: 'maps',
cwd: `${__dirname}/assets`
});
with error:
Error: ENOENT, assets\maps.json.714842314 not found in D:\myapp\resources\app.asar
The file is maps.json and exists inside assets folder. When I build my application using electron-packager
, for some reason, electron-store
tries to read the file as maps.json.<random number>
.
Maybe because of atomic writing feature in the conf
module? If I lock conf
in version 1.1.2 it works fine.
Thanks
It's easy to think that it would make for a simpler API. No need to initialize it first. I thought so too at first.
But imagine if it had been a singleton:
index.js
const config = require('electron-config');
const someComponent = require('./some-component');
config.setDefaults({
foo: true
});
…
config.get('foo');
//=> true
some-component.js
const config = require('electron-config');
…
config.get('foo');
//=> undefined
Note the undefined
. So you would have to be careful about setting the defaults before any app imports, which is easy to forget.
The following a much safer and explicit pattern:
config.js
const config = require('electron-config');
module.exports = new Config({
foo: true
});
index.js
const config = require('./config');
const someComponent = require('./some-component');
…
config.get('foo');
//=> true
some-component.js
const config = require('./config');
…
config.get('foo');
//=> true
Thoughts on this?
Hey There,
Using this in our Electron app, which is a React app.
When I run npm run build
I get the following error message:
Failed to minify the code from this file:
./node_modules/electron-store/index.js:6
Read more here: http://bit.ly/2tRViJ9
If you follow the link it says to:
Open an issue on the dependency's issue tracker and ask that the package be published pre-compiled.
Let me know your thoughts on this.
Thanks!
When the file that is passed to the store options is not a valid JSON, the contents of the file are overwritten to an empty object. Is there any built-in way to overcome this or should I check the validity of the file before calling the ctor of the store?
why not just use window.localStorage?
const Store = require('electron-store');
const appStore = new Store();
var item = {
"https://mail.google.com/mail/": {
"metadata": {
"name": default mail client"
}
}
};
appStore.set(item);
The default location for stores (~/.config/AppName
on linux) is not deleted when the app is uninstalled. Is this intentional? Do you have a recommendation for how to delete the data when the app is deleted?
Uncaught Exception:
TypeError: Expected string, got undefined
at module.exports.name ([...]IRCCloud.app/Contents/Resources/app.asar/node_modules/env-paths/index.js:49:9)
at ElectronConfig.Conf ([...]IRCCloud.app/Contents/Resources/app.asar/node_modules/conf/index.js:29:9)
at ElectronConfig ([...]IRCCloud.app/Contents/Resources/app.asar/node_modules/electron-config/index.js:11:3)
at setupConfig ([...]IRCCloud.app/Contents/Resources/app.asar/main.js:56:10)
at Object.<anonymous> ([...]IRCCloud.app/Contents/Resources/app.asar/main.js:60:16)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:456:32)
at tryModuleLoad (module.js:415:12)
at Function.Module._load (module.js:407:3)
env-paths expects a String, but conf is passing in an undefined opts.projectName
, because electron-config is setting opts.cwd
directly so it isn't needed.
This fails because the package.json isn't bundled into the asar file when built, so pkg-up finds nothing.
Not sure which package this should be fixed in.
Also, a fresh npm install results in this version tree:
└─┬ [email protected]
└─┬ [email protected]
└── [email protected]
conf depends on env-paths: ^0.2.0 which won't allow 0.3.0
Encryption was failing for me. Not sure how, but version [email protected] was installed.
Can you fail if encryptionKey is provided and conf ~= 1.3?
Version 2.0.0 seems not work on electron 4.
Module not found: Error: Can't resolve 'worker_threads' in write-file-atomic
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.