Help us understand the problem. What is going on with this article?

NodejsでJSONファイル読込時のpath指定方法はrequireとfs.readFileで違うので注意

More than 1 year has passed since last update.

結論

  • rootFolder
    • |---- Folder1
      • |---- target.json
      • |---- readJSON.js

上記のディレクトリ構造で、target1.jsonの内容を読み込むコードは下記の通り

target.json
{ "hoge" : "fuga" }
readJSON.js
var fs = require("fs");

var use_require_json = require('./target.json');
console.log(use_require_json.hoge); //=> "fuga"

var use_readFile_json = JSON.parse(fs.readFileSync('./Folder1/target.json', 'utf8'));
console.log(use_readFile_json.hoge); //=> "fuga"

ポイント

【Point1】
requireを使用する場合は、自ファイルと読込対象ファイルの相対pathを指定
例の場合、 readJSON.js と同ディレクトリに target.json があるので
./target.json
でOK

【Point2】
readFile(readFileSync) を使用する場合は、自ファイルがどこにあるかに関わらずrootからのpathを指定
例の場合、 target.json のrootからのpathである
'./Folder1/target.json'
を指定する

検証環境

・cloud9 + heroku
・node: 8.9.4
・npm: 5.6.0
・環境によって変わる可能性あり

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away