Node.jsでのfs.readFileSync()
以下のようなディレクトリ構成で作業をしているとしましょう。
│ main.js
│
├─commands
│ callhere.js //fs.readFileSync()を呼ぶファイル
│ other1.js
│ other2.js
└─config
config.json // 読み込みたいjsonファイル
さて、jsonファイルを読み込むためには、どのようにすればいいでしょうか。callhere.js
で
const jsonData = JSON.parse(fs.readFileSync("../config/config.json"));
とすればパスが通っていそうですよね。しかし、Node.js
をインストールしているディレクトリでは、この書き方ではエラーになってしまうのです。どうやら、この書き方では、現在のファイル(例ではcallhere.js
)が存在する位置を最上位のディレクトリとして設定してしまい、現在のディレクトリより外には移動できないシステムみたいです。
例だと、callhere.js
から、config
ファイルやmain.js
へfs.readFileSync()
ができないみたいです。
解決策: pathモジュールのpath.resolve(__dirname, " ")
というのを使うことで、この問題が解決できます。今回の例だと
const jsonData = JSON.parse(fs.readFileSync(path.resolve(__dirname,"../config/config.json")));
となります。シンプルに相対パスを指定して読み込むことができるようになります。