LoginSignup
8
8

More than 5 years have passed since last update.

パッケージングしたElectronアプリケーションでファイル操作時にpermission deniedになった場合の対処

Posted at

Electronでlowdbを使ってローカルのjsonファイルを読み書きしていたのですが、開発時は問題なく動いていたのにパッケージングしたアプリケーションではEACCESS permission denied と実行時エラーになりました。

const low = require('lowdb')
const storage = require('lowdb/file-sync')

const db = low('db.json', { storage })  // permission denied!!!

ルートディレクトリ見に行ってしまっているのかなと思い、./db.json を試してみましたがダメでした。ググるって見ると、__dirname を使えばいいよ!というポストを見つけたのですが、これもダメで・・・(ポストではelectronのバージョンがちょっと古かったのでそのせいかもしれません。)
ちなみに __dirname"/" になっていて、やはりルートディレクトリをみているようでした。

メインプロセス(main.js)でのほぼお決まりの mainWindow.loadURL(file://${__dirname}/app/index.html) ではちゃんとなっているっぽいのに・・・
と書きながら思ったのですが、レンダラプロセスだからダメだった?今度調べよう。

でようやく対処法ですが

const remote = require('remote');
const app = remote.require('electron').app;
// pathを使っているのは半分好みなので必須ではありません。
const path = remote.require('path');
const low = require('lowdb')
const storage = require('lowdb/file-sync')
const dbFilename = path.join(app.getAppPath(), 'db.json');
const db = low(dbFilename, { storage });

要は自分の場所が分からないならappに教えてもらおうということです。

8
8
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
8
8