16
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Electronを使ってローカルファイルにアクセスするアプリを作ってみる

Posted at

開発環境

  • node.js
  • Electron1.6.7

Electronの魅力の一つにWebアプリケーションの作りで、ローカルファイルにアクセスできる点があるという。
ならば、と作ったのがこのシンプルなアルバム。

20170522.gif

うーむ、当初はわざわざJavaScriptでローカルアプリ作る必要あんの?って思ったけど、思ってるより作りやすいな・・・インターフェースとサーバ側を同じ言語が使えると言うのが想像以上にやりやすいです。

ソースはgithubに上げておきました。
album-app

Dialogの使い方

propertiesに配列でセットすれば、色んな使い方が出来るので公式を確認して試すといいかも

index.html
<javascript>
    const {ipcRenderer} = require('electron');
    const {dialog} = require('electron').remote;

    function openDialog(){
      var options = {
        title : "open folder",
        properties : ['openDirectory']
      };
      dialog.showOpenDialog(options, function(filenames) {
        ipcRenderer.send('mul-async-dialog', filenames);
        ipcRenderer.on('mul-async-dialog-replay', (event, arg) => {
          msg(arg);
        });
      });
    }

</javascript>
main.js
var ipc = require('electron').ipcMain;

ipc.on('mul-async-dialog', function(event, arg) {
    // console.log(arg[0]);
    if (!arg) {return;} // cancel selected
    path = arg[0];
    index = 0;
    fileRead(); //filePathに画像のパスをセットする
    event.sender.send('mul-async-dialog-replay', filePath);
  }
);

アルバムなので本当は写真の一覧でも表示すればいいのだろうけど、面倒だったのでタップすれば次の写真を読み込むようにしました。一方的に進めないけど・・・。DOMContentLoadedはhtml側の読み込みが終わってから処理しろよって意味です。これがないと本体より前に書いたjavascriptでこけたので。

index.html
<javascript>
     function getReadASync() {
      ipcRenderer.send('mul-async');
      ipcRenderer.on('mul-async-replay', (event, arg) => {
        msg(arg);
      });
    }

    function msg(msg) {
      info.src = msg;
    }

    document.addEventListener("DOMContentLoaded", function(){
      document.getElementById("imgArea").addEventListener("click", function(){
        getReadASync(); 
      });
    }, false);
</javascript>
<body>
    <div id ="imgArea">
      <img id="info" width="800" height="550"></img>
    </div>

ここらへんの技術は正直難しそうで敬遠してたところもあるけど、いざ使ってみるとなかなか面白いのでもう少し追っかけてみようと思います。

16
20
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
16
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?