4
4

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 3 years have passed since last update.

TypeError: fs.existsSync is not a functionの対処法(強引な解決方法)

Last updated at Posted at 2019-01-22

環境

仮想環境のOS:Ubuntu
Electron 1.8.2
node v8.10.0

状況

ReactとElectronでのアプリ作ってる時に、自分が書いたプログラムに問題があるわけではなさそうなんだけど。。。
プログラムの中で、require('electron')すると、エラーが出た

TypeError: fs.existsSync is not a function
(anonymous function)
node_modules/electron/index.js:7
   4 | 
   5 | var pathFile = path.join(__dirname, 'path.txt');
   6 | 
>  7 | if (fs.existsSync(pathFile)) {
   8 |   module.exports = path.join(__dirname, fs.readFileSync(pathFile, 'utf-8'));

解決方法

こういう、「関数ではないよ」みたいな謎のエラーは他にもよく見たことあるけど、今回は特殊。Electron単体ではなくReactと組み合わせて開発してるので、fsモジュールは使えない。デスクトップアプリを作るとはいえweb感覚での開発なので、ファイルの入出力はできない。

なので、とりあえずコメントアウトする。

index.js
var fs = require('fs')
var path = require('path')

var pathFile = path.join(__dirname, 'path.txt')
/*
if (fs.existsSync(pathFile)) {
  module.exports = path.join(__dirname, fs.readFileSync(pathFile, 'utf-8'))
} else {
  throw new Error('Electron failed to install correctly, please delete node_modules/electron and try installing again')
}
*/

例えば、何かのAPIを使う上でアクセストークンが書かれたjsonファイルをfsモジュール使ってファイル取得しようとしても同じようなエラーが出るので、jsonファイル使わず直接文字列で指定して解決したこともありました。
もっと良い方法を知っている方いれば教えていただけると幸いです。

感想

Reactでfsモジュールは使えないってことを知れたのはかなりでかい。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?