7
1

More than 1 year has passed since last update.

【JavaScript】Node.jsでのfs.readFileSync()の相対パス

Posted at

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.jsfs.readFileSync()ができないみたいです。

解決策: pathモジュールのpath.resolve(__dirname, " ")

というのを使うことで、この問題が解決できます。今回の例だと

const jsonData = JSON.parse(fs.readFileSync(path.resolve(__dirname,"../config/config.json"))); 

となります。シンプルに相対パスを指定して読み込むことができるようになります。

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