LoginSignup
7
8

More than 5 years have passed since last update.

electronでsocket.ioを使うとレンダープロセスでrequireできない?!

Last updated at Posted at 2015-10-24

背景

IPアドレスを取得するNode.jsのモジュールを自作してelectronを動かしているPCのアドレスを表示して、スマホからこのアドレスにアクセスしてその後、socket.ioでWebSocket通信させようと試みていた。

ところが、レンダープロセスで、requireして自作のnpmモジュールが読み込めない。

socket.ioはfile://だと上手くいかない

通常のElectronではメインプロセスが話のコードで

mainWindow.loadUrl('file://'+__dirname+'/index.html');

という具合に、file://でレンダープロセスのlocation.hrefを指定する。
ところが、socket.ioだと、この指定だと、動かない。真面目に、コード読んでないが、
おそらくsocket.ioのクライアントが話のコードでlocation.hrefに依存した処理がある模様。これがfile://だとダメで、httpもしくは、httpsを指定する必要がある。

ということで、socket.ioを使う場合、以下の様になる。

mainWindow.loadUrl('http://127.0.0.1:3000');

レンダープロセスではfile://

ところが、レンダープロセスではhttp://やhttps://では、
requireで任意のモジュールが呼び出せない。
not foundとエラーとなってしまう。

対策

メインプロセス側

メインプロセス側で__dirnameにpackage.jsonのmainに指定したjsへのパスが格納されている様なので、これをレンダープロセス側に渡す。

mainWindow.loadUrl('http://127.0.0.1:3000/s?d='+__dirname);

レンダープロセス側

module.paths.push(location.search.slice(3)+'/node_modules');
const localip = require('node-ore-module');

参考資料

関連記事

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