LoginSignup
26
30

More than 5 years have passed since last update.

Electronで設定ファイルを扱う

Last updated at Posted at 2016-12-13

electron-config一択。

sindresorhus/electron-config: Simple config handling for your Electron app or module

性質上設定ファイルは起動時に読み込みや終了時に設定の保存などに使われる。
ここでの処理がコールバックスタイルで書かれるelectron-json-storageは扱いづらいだけと個人的には思う。

名前の変更

今(2018-06-13)はelectron-storeに名前が変わっています。

sindresorhus/electron-store: Simple data persistence for your Electron app or module - Save and load user preferences, app state, cache, etc

インストール

$ npm install --save electron-config

使い方

公式のUsageそのままだが、使い方に迷うことないだろう。
面白い点としてdot-notationをサポートしてる。
いちいちオブジェクトを作らずfoo.barと文字列で保存できるのは便利だ。

もちろん、メインとレンダラープロセスの両方で使える。

const Config = require('electron-config');
const config = new Config();

config.set('unicorn', '🦄');
console.log(config.get('unicorn'));
//=> '🦄'

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

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

色々省略したけどだいたいこんな感じにすれば、移動時やリサイズ時にウィンドウの設定が保存される。
それを起動時に読む込んでやるだけで前回のウィンドウが復元される。

const Config = require('electron-config')

const config = new Config({
    defaults: {
        bounds: {
            width: 800,
            height: 600,
        },
    },
})

function createMainWindow() {
    const {width, height, x, y} = config.get('bounds')
    const win = new BrowserWindow({title: 'sample', width, height, x, y})

    win.loadURL(`file://${__dirname}/index.html`)

    ['resize', 'move'].forEach(ev => {
        win.on(ev, () => {
            config.set('bounds', win.getBounds())
        })
    })
}

app.on('ready', () => {
    mainWindow = createMainWindow()
})
26
30
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
30